Validation closure not firing?

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)
    {
        IlluminateSupportFacadesValidator::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)
   {
        IlluminateSupportFacadesValidator::make($request->all(), [
            'trainer' => 'required',
        ]);

        dd('NO ERROR??');
   }

I get as expected:

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

What am I missing?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 IlluminateContractsValidationImplicitRule (see https://laravel.com/docs/8.x/validation#implicit-rules)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x