vendredi 16 avril 2021

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)
    {
        \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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire