Hello, web developers! In this article, we'll see how to create form request validation in laravel 10. Laravel provides several different approaches to validate your application's incoming data.
For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request
Artisan CLI command.
In this guide, I'll walk you through the step-by-step process of creating laravel 10 form request validation.
First, make sure you have Laravel 10 installed. If not, you can install it via Composer by running:
composer create-project --prefer-dist laravel/laravel myproject
Laravel provides a convenient way to validate incoming HTTP request data using form requests. To create a form request, run the following Artisan command:
php artisan make:request MyFormRequest
Replace MyFormRequest
with your desired name for the request.
Open the generated form request file located at app/Http/Requests/MyFormRequest.php
. Inside the rules()
method, define the validation rules for your form fields. For example:
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed',
];
}
You can also define the authorization logic in the authorize()
method if needed. For example, allowing only authenticated users to submit the form
public function authorize()
{
return Auth::check();
}
Laravel automatically handles validation errors and redirects the user back to the previous page, with error messages flashing to the session. You can display these error messages in your views using Blade directives like @error('field')
.
To use the form request in your controller, simply type it using the controller method where you handle the form submission. For example
use App\Http\Requests\MyFormRequest;
public function store(MyFormRequest $request)
{
// The request has passed validation; continue processing
}
You might also like:
- Read Also: Laravel 10 With Vue JS CRUD Operation
- Read Also: How to Add Select2 in Laravel 10 Example
- Read Also: How to Validate Form using AJAX in Laravel 10
- Read Also: How to Create Livewire Multi Step Form Wizard in Laravel 10