首页 > 解决方案 > 为什么 Laravel 5.6 中的自定义验证不起作用?

问题描述

我使用 php artisan make:rule 创建了一个自定义规则,将其设置在控制器中,但它不起作用。可能是什么问题?

class CheckDeliveryDate implements Rule
{
    public $client_id;
    private $is_after_midday;
    private $error_messge;

    public function __construct(int $client_id)
    {
        $this->client_id = $client_id;
        $this->is_after_midday = Carbon::now()->greaterThan(Carbon::now()->midDay());
        $this->error_messge = 'Error';
    }

    public function passes($attribute, $value)
    {
        $delivery_date = Carbon::parse($value);

        if ($delivery_date->isToday()) {
            $this->error_messge = 'Error';

            return false;
        }
        if ($delivery_date->endOfDay()->isPast()) {
            $this->error_messge = 'Error';

            return false;
        }

        return true;
    }

    public function message()
    {
        return $this->error_messge;
    }
}

在控制器中我设置方法规则:

public function rules($client_id)
{
    return [
        'orders.*.positions.*.delivery_time' => [
            'required',
            'date',
            new CheckDeliveryDate($client_id)
        ],
    ];
}

当我存储订单时,validator->fails() 返回“false”。

$validator = Validator::make(
    $request->all(),
    $this->rules($client_id)
);

我尝试在规则中设置 dd 或转储,但不起作用。我的错误在哪里?

标签: phplaravel

解决方案


如 laravel 文档(https://laravel.com/docs/5.8/validation#custom-validation-rules)所述,您不应该将参数传递给您的自定义规则实例。Laravel 为你做到了。

因此:

new CheckDeliveryDate($client_id)

变成:

new CheckDeliveryDate

祝你今天过得愉快 !


推荐阅读