Search code examples
laravellaravel-6laravel-validation

Laravel Valiadtion array must have one element with a certain value


Imaging having the following input for a form request validation.

[
    'relations' =>
        [
            [
                'primary' => true,
            ],
            [
                'primary' => false,
            ],
        ],
],

Is there any validation that makes it possible to secure that at least one of the relations models have primary set to true? More perfect if it could secure only one element is true. This problem seems like it could have existed before.

So if we only see the input for relations, this should pass.

[
    'primary' => true,
],
[
    'primary' => false,
],

This should fail in validation.

[
    'primary' => false,
],
[
    'primary' => false,
],

Solution

  • Try an inline custom rule:

    public function rules()
    {
        return [
            'relations' => function ($attribute, $relations, $fail) {
                $hasPrimary = collect($relations)
                    ->filter(function ($el) {
                        return $el['primary'];
                    })
                    ->isNotEmpty();
    
                if ( ! $hasPrimary)
                {
                    $fail($attribute . ' need to have at least one element set as primary.');
                }
            },
    
            // the rest of your validation rules..
        ];
    }
    

    Of course, you could extract this to a dedicated Rule object, but you get the idea.