1

I'm trying to make a custom rule against an array of checkboxes. The request data comes in properly like

cbarray => [
  cb1 => null,
  cb2 => true,
  cb3 => true,
]

I'm trying to make a validation rule that fails if all the checkboxes are set to true.

Then I've added it to my laravel rules as

'job-payment.*' => [ new NotAllTrue ],

expecting that this would be sent into my rule as an array of values, but it appears to only send in the first attribute and value.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NotAllTrue implements Rule
{    
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return !array_reduce($value, function ($carry, $val) {
            return $carry && $val;
        }, true);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'These cannot all be true.';
    }
}
2
  • 2
    What happens if you don't add the .* to the rule? Commented Apr 12, 2018 at 14:29
  • That was it, thanks @Joe Commented Apr 12, 2018 at 14:42

1 Answer 1

1

If you want to pass the whole array you have to write this way:

'job-payment' => [ new NotAllTrue ],

If you want to independently validate each element of the array then:

'job-payment.*' => [ new NotAllTrue ],
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.