Bolek Lolek
Bolek Lolek

Reputation: 619

Laravel array validation with custom rule

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;
}

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

Upvotes: 2

Views: 1377

Answers (1)

Luciano
Luciano

Reputation: 2196

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;
    }
}

Upvotes: 2

Related Questions