How do I validate requests in Laravel?

In Laravel, validating requests is a crucial step to ensure that the data being entered by the user meets the required criteria before processing. Laravel provides a robust validation mechanism that simplifies the task of validating incoming requests.

To validate a request, you can use the built-in validation methods either in a controller or as a Form Request. Here's a basic example of how to validate a request in a controller:

public function store(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|min:8|confirmed', ]); // The incoming request is valid... // Proceed to create the user or perform the next action. }

You can also create a custom Form Request by running the following artisan command:

php artisan make:request StoreUserRequest

In the newly created request class, you can define your validation rules:

public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|min:8|confirmed', ]; }

This way, you can keep your code clean and manage validations in a separate class.


Laravel validation request validation in Laravel Laravel form request Laravel validate request examples