Easy Way To Validate Laravel API Request And Sending
JSON Response

Web Developer Kaustubh
2 min readOct 27, 2019

--

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.

Laravel API Code

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

Error message when validation fails

--

--

Web Developer Kaustubh
Web Developer Kaustubh

Written by Web Developer Kaustubh

Sr.Web developer. love to code. PHP , Javascript, Mysql, Laravel, Jquey, git, project planing,Linux

No responses yet