本文介绍了使用自定义规则的Laravel数组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CustomFormRequest中,我有这样的内容:

In CustomFormRequest i have something like this:

public function rules(): array
{
    return [
        'events' => ['array'],
        'events.*.type' => ['required'],
        'events.*.data' => [app(SomeRule::class)],
    ];
}

SomeRule:

public function passes($attribute, $value): bool
{
    var_dump($attribute);//events.0.data
    var_dump($value);exit;
}

SomeRule::passes中,我需要访问events.X.type(因此对于events.5.data,我需要events.5.type).有什么想法吗?

In SomeRule::passes i need to have access to events.X.type (so for events.5.data i need events.5.type). Any ideas?

推荐答案

用户在我的问题中发表了评论,您可以使用此代码来完成此操作,在这种情况下,它类似于

As a user commented in my question Validating array in Laravel using custom rule with additional parameter, you can do it with this code, in your case it would be something like

class SomeRule implements Rule
{
    public function passes($attribute, $value)
    {
        $index = explode('.', $attribute)[1];
        $type = request()->input("events.{$index}.type");

        return someConditional ? true : false;
    }
}

这篇关于使用自定义规则的Laravel数组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:10