Laravel request validation required_if with multiple conditions

Viewed 504

I want to implement the validation use the Laravel required_if with multiple conditions.

I have an array of objects and want to validate that the attribute of the object will be required if the type=image and the isUsed of the object is false.

return request()->validate([
    'sets.*.attribute' => 'required_if:type=image && sets.*.isUsed=false',
]);

How can I archive it?

2 Answers

You can use Rule

use Illuminate\Validation\Rule;

...

Rule::requiredIf(function () use ($request) {
        $sets = collect($request->input('sets', []));

        return $request->input('type') === 'image'
               && $sets->filter(fn($set) => $set['isUsed'])->isEmpty();
}),

Assuming $sets correspond to the following value and isUsed must be false on each set.

$sets = collect([
    ['isUsed' => false],
    ['isUsed' => false],
    ['isUsed' => false],
]);

More info in the documentation: https://laravel.com/docs/8.x/validation#rule-required-if


Note that I'm using the short arrow syntax from PHP7.4 fn() => ... if you're on a lower PHP version you will have to use standard anonymous function function () { ... }

I found a solution that can be applied for the request validation, it's more simple to use with the current implementation.

return request()->validate([
    'sets.*.attribute' => function ($attr, $value, $fail) {
        if (request()->input('type') == 'image' && !request()->input('sets')[explode('.', $attr)[1]]['isUsed'] && empty($value)) {
            $fail('The ' . $attr . ' is required.');
        }
    },
]);
Related