1

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,
],
3
  • Are you using a Form Request or validating inside a controller? Commented Feb 14, 2020 at 14:51
  • FormRequest, but shouldn't matter? you can achieve the same things Commented Feb 14, 2020 at 14:58
  • I know, just to be on point on the answer. Commented Feb 14, 2020 at 15:10

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.