When you’re performing some user input validation in PHP, and the input isn’t compliant to your rules, you’ll need to inform the user about what went wrong. Setting an appropriate HTTP response along with an error message is good practise. And it’s easy with Laravel.
Assuming you have some routing in place – here’s an example of something you might setup inside a controller when the input is invalid:
return Response::json( array( 'error' => true, 'msg' => "We didn't like your input!" ), 400 );
We respond with a 400 (Bad Request).
You could pass another associative array to msg
if you needed to return several error messages all at once. For example:
return Response::json( array( 'error' => true, 'msg' => array( 'email' => "Invalid email address", 'password' => "Password is required" ) ), 400 );
Both set the response header to application/json
and send the arrays as JSON across to the client. This makes it easy to implement some JavaScript in order to display the errors.