Validation closure not firing?

Viewed 305

I want to create a custom validation using closures in Laravel 5.6 as explained in the docs: https://laravel.com/docs/5.6/validation#using-closures

That is my code:

   public function store(Request $request)
    {
        \Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => [
                function ($attribute, $value, $fail) {
                    return $fail($attribute . ' is invalid.');
                },
            ],
        ]);

        if ($validator->fails()) {
          dd($validator->messages());
        }

        dd('NO ERROR??');
   }

Testing it using

$this->post('/my_test_route', []);

Returns

NO ERROR??

Why is this? If I change the code to

   public function store(Request $request)
   {
        Illuminate\Support\Facades\Validator::make($request->all(), [
            'trainer' => 'required',
        ]);

        dd('NO ERROR??');
   }

I get as expected:

Illuminate\Support\MessageBag^ {#2408
  #messages: array:1 [
    "trainer" => array:1 [
      0 => "The trainer field is required."
    ]
  ]
  #format: ":message"
}

What am I missing?

1 Answers

Found the problem. Because trainer was not given as an input, the custom validation method was not executed!

Adding trainer as parameter worked:

$this->post('/my_test_route', ['trainer' => 'test']);

Or as an alternative use:

'trainer' => [
               'required',
                function ($attribute, $value, $fail) {
                    return $fail($attribute . ' is invalid.');
                },
            ],

Or, if you want to execute the validation method even if the parameter is not provided, and you don't want to make it required, then your custom rule should implement Illuminate\Contracts\Validation\ImplicitRule (see https://laravel.com/docs/8.x/validation#implicit-rules)

Related