在 Laravel 中添加自定义验证时,class 闭包的对象无法转换为字符串

Object of class Closure could not be converted to string when adding custom validation in Laravel

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

(1/1) ErrorException Object of class Closure could not be converted to string in ValidationRuleParser.php line 107

请协助

控制器

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');
            }
        }],
    ]);
}

正如您在评论中提到的,您正在使用不支持回调验证规则的 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);        
});