Validating array in Laravel using custom rule with

2019-05-29 03:09发布

问题:

I'm working with Laravel 5.7 and I need to validate a phone length by using 2 inputs (prefix+number). The total digits has to be 10 always.

I'm using this custom rule for other projects which works fine:

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;

class PhoneLength implements Rule
{
    public $prefix;

/**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($prefix = null)
{
    //
    $this->prefix = $prefix;
}

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    //
    return strlen($this->prefix)+strlen($value) == 10 ? true : false;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'El Teléfono debe contener 10 dígitos (prefijo + número)';
}
}

In my controller I do something like

$validatedData = $request->validate([
  'prefix' => 'integer|required',
  'number' => ['integer','required', new PhoneLength($request->prefix)],
]);

Now I need to make use of arrays, so my new validation looks like

$validatedData = $request->validate([
  'phones.*.prefix' => 'required',
  'phones.*.number' => ['required', new PhoneLength('phones.*.prefix')],
]);

The above code doesn't work at all, the parameter is not being sent as expected. How can I send an array value? Of course I need to get the values from the same array element, so if phones[0].number is under validation, the prefix phones[0].prefix is needed.

I've found this question, but I refuse to believe that is not possible to do in a "native" way: Laravel array validation with custom rule

Thanks in advance

回答1:

You could get $prefix from the request itself:

class PhoneLength implements Rule
{
    public function passes($attribute, $value)
    {
        $index = explode('.', $attribute)[1];
        $prefix = request()->input("phones.{$index}.prefix");
    }
}

or pass the $request in the PhoneLength rule constructor, then use it.