使用带有附加参数的自定义规则验证 Laravel 中的数组

Luc*_*ano 7 arrays validation rules laravel

我正在使用 Laravel 5.7,我需要使用 2 个输入(前缀+数字)来验证电话长度。总位数必须始终为 10。

我正在将此自定义规则用于其他工作正常的项目:

<?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)';
}
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我做了类似的事情

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

现在我需要使用数组,所以我的新验证看起来像

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

上面的代码根本不起作用,参数没有按预期发送。如何发送数组值?当然我需要从同一个数组元素中获取值,所以如果phones[0].number正在验证中,phones[0].prefix则需要前缀。

我发现了这个问题,但我拒绝相信这是不可能以“原生”方式做到的: Laravel array validation with custom rule

提前致谢

小智 12

您可以$prefix从请求本身得到:

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

$request或在规则构造函数中传递PhoneLength,然后使用它。