首页 > 解决方案 > 在 Laravel 中添加自定义验证时,类 Closure 的对象无法转换为字符串

问题描述

我正在研究 Laravel 中的一些自定义验证规则,其中添加了一些自定义验证 2 个日期,其中返回日期必须在出发日期后 6 天,当我添加自定义验证时,我不断收到以下错误:

(1/1) 在 ValidationRuleParser.php 第 107 行中,Closure 类的 ErrorException 对象无法转换为字符串

请协助

控制器

public function validatePlanEntries(Request $request)
{
    $validation = $this->validate($request, [
        'departure_date' => 'required|date|after:now',

        //Must be 6 days after departure date
        'return_date' => ['required', 'date', function ($attribute, $value, $fail) {
            if (strtotime($value) < strtotime(request('departure_date')) + 518400) {
                $fail('Departure date invalid');
            }
        }],
    ]);
}

标签: laraveldatecustomvalidator

解决方案


正如您在评论中提到的,您使用的 Laravel 版本不支持回调验证规则,不幸的是,您可以做到这一点的唯一方法是使用新规则扩展验证器。

将此添加到您的服务提供商之一(例如AppServiceProvider

public function boot() {
     //Other boot things

    $validator = app()->make(\Illuminate\Validation\Factory::class);
    $validator->extend('return_date_after', function ($attribute, $value, $parameters, $validator) {
          $otherAttribute = array_get($parameters, 0);
          $days = array_get($parameters, 1, 6); //default 6 days
          $otherValue = array_get($validator->getData(), $otherAttribute);
          if (strtotime($value) < strtotime($otherValue) + $days*24*60*60) {
            return false;
          }
          return true;
    });

    $validator->replacer('return_date_after', function ($message, $attribute, $rule, $parameters) {
          return 'Your return date must be '.array_get($parameters,1,6).' days after your '.array_get($parameters, 0);
   });
}

然后您可以将此自定义规则用作:

  $validation = $this->validate($request, [
        'departure_date' => 'required|date|after:now',

        //Must be 6 days after departure date
        'return_date' => ['required', 'date', 'return_date_after:departure_date,6' ]
    ]);

请注意,替换器$message中的 来自 ,resources/lang/<locale>/validation.php因此您可以在其中添加一个条目,例如“return_date_after”并在替换器中对其进行操作,而不是返回静态文本。例如:

"return_date_after" => "Your :attribute must be :days days after your :other_attribute"

然后你的替代者可以是:

 $validator->replacer('return_date_after', function ($message, $attribute, $rule, $parameters) {
      return str_replace([ ":days", ":other_attribute" ], 
          [ array_get($parameters, 1, 6), array_get($parameters,0) ], 
          $message);        
});

推荐阅读