Lumen provides several different approaches to validate your application's incoming data. By default, Lumen's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.
To learn about Lumen's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user.
Now we are ready to fill in our store method with the logic to validate the new blog post. If you examine your application's base controller (Laravel\Lumen\Routing\Controller) class, you will see that the class uses a ValidatesRequests trait. This trait provides a convenient validate method in all of your controllers.
So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Lumen will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Lumen will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that an $errors variable will always be available in all of your views on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation.
In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Lumen will not generate a redirect response. Instead, Lumen generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function.
The field under validation must match the given format. The format will be evaluated using the PHP date_parse_from_format function.
The field under validation must be present if the anotherfield field is equal to any value.
The field under validation must be a valid URL according to PHP's filter_var function.