Search code examples
phplaravellaravel-validation

How to check if a specific value exists in a given array?


Here is the array:

<input name="gallery[0][file]" value="file"> // could be empty or zip or image file 
<input name="gallery[0][main]" value="false">  // one of main must be true

<input name="gallery[1][file]" value="file"> // could be empty or zip or image file
<input name="gallery[1][main]" value="true"> // one of main must be true

<input name="gallery[2][file]" value="file"> // could be empty or zip or image file
<input name="gallery[2][main]" value="false"> // one of main must be true

I want to make sure one of the "main" inputs is true on the list.

How can do I it? Here are my current rules

return [
    'gallery' => 'required|array',
    'gallery.*.file' => 'required|max:30000',
    'gallery.*.main' => 'required|in:true,false',
];

Solution

  • Can try closure for custom validation

    public function rules()
    {
        return [
            'gallery' => ['required', 'array'],
            'gallery.*.file' => ['required', 'max:30000'],
            'gallery.*.main' => [
                'required',
                function($attribute, $value, $fail) {
                    $count = 0;
                    foreach(request()['gallery'] as $item) {
                        if(in_array($item['main'], [1, '1', true, 'true'], true)) {
                            $count++;
                        }
                    }
                    if($count === 0) {
                        $fail('At least one main must be true');
                    }
                }
        ];
    }