How to show Validation message in Controller?
Solution 1
I noticed none of the provided examples here actually work! So here you go. This was my found solution after realizing that validator->messages()
returns a protected object which isn't retrievable.
if ($validator->fails())
{
foreach ($validator->messages()->getMessages() as $field_name => $messages)
{
var_dump($messages); // messages are retrieved (publicly)
}
}
I would reference MessageBag, which is what messages()
returns. And for additional acknowledgement of the Validator class - reference this.
Solution 2
$validation->fails()
returns a boolean of whether or not the input passed validation. You can access the validation messages from $validation->messages()
or pass them to the view where they will be bound to the $errors
variable.
See the validator docs.
Related videos on Youtube
Arryangga Aliev Pratamaputra
I’m a web and mobile developer with over 5 years of professional experience in the software industry. I specialize in creating custom web & mobile app for other businesses, focusing primarily on front end development (ReactJS, Preact, etc). I also blog on topics relating to web development, life, remote work, and work-life balance. Besides working, I like to provide a light talk about web development in the local community, here is some title of my presentation : - Progressive Web Apps (Google Kejar) - 2018 - Laravel Multisite - 2017 - Biznet Neo Geo - Introduction to React Native - 2017 - Surabayadev - Introducing to Restful API with Laravel - 2016 - Dilo Telkom - Repository Pattern in Laravel - 2016 - SurabayaDev & Kopidev - Introducing to Laravel - Aug 2015 - Laravel Surabaya
Updated on September 15, 2022Comments
-
Arryangga Aliev Pratamaputra over 1 year
I have tried showing an error message in a Controller and it doesn't work, but when I use
dd
, it works.My Code:
if ($validation->fails()) { /*Doesn't work foreach ($validation->fails() as $messages) { $messages // Doesn't work } */ dd($validation->errors); //This works }
-
Arryangga Aliev Pratamaputra almost 11 yearscan you tell my how do that? i dont want to pass them into the view
-
Dwight almost 11 yearsIn your controller you can loop through the validation messages as such:
foreach($validation->messages() as $message) { /**/ }