jeudi 12 avril 2018

Custom rule against input array in Laravel 5

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.';
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire