Dealing with request validation and error messages
The Laravel framework offers us many ways to show error messages, and, by default, Laravel's base controller class uses a ValidatesRequests
trait that provides methods to validate the incoming HTTP request, including many default rules such as required, email format, date format, string, and much more.
Note
You can read more about the possible validation rules at https://laravel.com/docs/5.6/validation#available-validation-rules.
It is pretty simple to use request validation, as we can see in the following code block:
$validatedData = $request->validate([ 'field name' => 'validation rule, can be more than one', 'field name' => 'validation rule', 'field name' => 'validation rule', ... ]);
For example, let's see how we can validate the incoming request to the bikes
endpoint using the HTTP POST
method to localhost:8081/api/bikes
.
The validation code will look as follows:
$validatedData = $request->validate([ 'make' => 'required'...