Introduction
In Laravel, data validation is an important part of ensuring that your application only accepts valid input. While you can perform data validation in your controller methods, it’s often better to use custom requests to handle data validation. In this post, we’ll explore how to use custom requests for data validation in Laravel.
Step 1: Creating a Custom Request
To create a custom request, you can use the make:request
Artisan command. For example, if you want to create a custom request for a Student model, you can run the following command:
php artisan make:request StudentRequest
This will create a new file StudentRequest.php
in the app/Http/Requests
directory. In this file, you can define the rules for validating the student data.
Step 2: Defining Validation Rules
In the rules
method of your custom request, you can define the validation rules for the student data. For example, if you want to require that the student’s name and email are provided and that the email is a valid email address, you can define the rules as follows:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
];
}
Step 3: Handling Failed Validation
In Laravel, when a user submits a form and validation fails, Laravel will redirect the user back to the previous page with an error message indicating which fields failed validation. To display these errors in the view, you can use Laravel’s $errors
variable and a conditional statement to check if there are any validation errors, and then loop through the errors to display them in a user-friendly manner.
To display multiple errors
@if ($errors->has('field_name'))
<ul>
@foreach ($errors->get('field_name') as $error)
<span class="text text-danger">{{ $error }}</span>
@endforeach
</ul>
@endif
To display single error.
@if ($errors->has('field_name'))
<span class="text text-danger">{{ $errors->first('field_name') }}</span>
@endif
Step 4: Using the Custom Request in the Controller
To use your custom request in a controller method, you can simply type-hint the request in the method signature. For example, if you have a store
method for creating a new student, you can define it as follows:
public function store(StudentRequest $request)
{
// Create a new student using the validated data
$student = new Student;
// Save the student to the database
$student->save();
// Redirect to the students index page
return redirect()->route('students.index');
}
Conclusion:
Using custom requests for data validation in Laravel can help simplify your controller logic and ensure that your application only accepts valid input. By defining the validation rules in a separate request class, you can also make your code more reusable and easier to maintain.