Easy Way To Validate Laravel API Request And Sending
JSON Response
When working on API in laravel we expect response in JSON.Many times developer get stuck in response while sending validation message back.
There are different method to send validation response back but
this is one of the easy method to send JSON response when API
request fail validation.
Explanation:- In above code we validate incoming request from API.
we check name and age input parameter if it is absent then
above code will throw validation error in JSON format.
$validator->fails()
Above line check whether validation fail or not,
$validator->errors()->all()
returns all validation messages in array.
implode(‘ ‘,$validator->errors()->all())
this line convert all validation messages from array into string for displaying message.
so if validation fails then we will get following error message