Introduction to Validations in Laravel
Validating data is a key part of website and app development because it ensures that user information is exactly as we want it to be. When it comes to Laravel and the famous Laravel Form Requests, this validation is essential to maintain the integrity and security of the data that our application receives.
Laravel has a built-in validation system that makes defining rules, custom error messages, and user feedback a breeze. This makes development more productive and user-friendly.
In this post, we’ll dive into validation in Laravel and present practical examples for your project.
Let’s start with a general look at the validation rules available in Laravel and then move on to real-world examples of how to apply them in different situations.
Basic Usage of Laravel Validation
Validation is important to ensure that the data entered into your app is reliable. Laravel has a built-in validation system that makes this task easier. Let’s see how to use Laravel Validation with some examples.
If you still need an introduction to using validation in Laravel, I recommend you start with this post or of course you can check the official documentation (in English).
Defining Validation Rules
To begin, you need to define validation rules for each field in your form. This can be done in the Controller that processes the form.
In the example below, we are validating a login form:
use Illuminate \ Support \ Facades \ Validator ;
$validator = Validator::make($request->all(), [
'email' => 'required|email' ,
'password' => 'required|min:6' ,
]);
In this example, we are using the class Validator
to create a validation object. We are validating two fields: email
and password
. The rule required
ensures that these fields are populated, while email
checking that the field email
contains a valid email address and min:6
ensuring that the password is at least 6 characters long.
Checking If Validation Passed
After defining the validation rules, you need to check whether the validation was successful or not. This is usually done as follows:
if ($validator->fails()) {
return redirect ( 'login' )
-> withErrors ($validator)
-> withInput();
}
In this example, we are checking to see if validation failed. If validation fails, we redirect the user back to the login page, with the error messages and previous input data, so the user can see what went wrong and correct the errors.
Or if you are building an API in Laravel, you can use this alternative:
if ($validator->fails()) {
return response()->json([ 'errors' => $validator->errors()], 400);
}
The basics of validation in Laravel are easy to use, and you can use it to ensure that the data entered into your app is exactly the way you want it to be. As you develop, you can explore more advanced validation rules and customizations to suit your project’s needs.
Creating Laravel Form Requests
In Laravel, Form Requests are a fundamental part of data validation. They are used to validate the data submitted via forms before it is processed by the controller. Using Form Requests helps keep your code much cleaner and more organized by centralizing the validation logic into separate classes.
Here are the basic steps to create Form Requests in Laravel:
- Creating a Form Request:
To create a Form Request, you can use the commandartisan make:request
. Open your terminal and run the following command, replacing “ExampleRequest” with the name you want to give your Form Request:
php artisan make: request ExampleRequest
This will create a new file in app/Http/Requests
with the name ExemploRequest.php
. This class will be used to define the validation rules for your form.
- Defining validation rules:
Open the fileExemploRequest.php
you just created. Inside this class, you can define validation rules in the methodrules()
. For example, if you are creating a Form Request to validate a user registration form, your validation rules might look like this:
public function rules ()
{
return [
'name' => 'required|string|max:255' ,
'email' => 'required|email|unique:users,email' ,
'password' => 'required|string| min:6|confirmed' ,
];
}
In this example, we are validating that the ‘name’ field is required and a string with a maximum of 255 characters, that the ‘email’ field is required, a valid and unique email address in the ‘users’ table, and that the ‘password’ field is required, a string with a minimum of 6 characters and that the password confirmation matches.
- Using the Form Request in your controller:
Now that you have created your Form Request, you can use it in your controller to validate the form input data. For example:
public function store (ExampleRequest $request)
{
// If the code has reached this far, the data has been validated successfully.
// You can continue processing the data.
}
Laravel automatically injects the Form Request( ExemploRequest
) instance and checks if the data is valid before executing the method store()
.
By following these steps, you can create Form Requests in Laravel to ensure that the data entered into your forms is verified easily and securely. This is like having a bodyguard for your application, preventing issues and keeping your application solid and reliable.
Customizing Validation Error Messages
Customizing validation error messages in Laravel is a good practice to make the user experience more informative and friendly. Laravel allows you to customize error messages for each validation rule, which makes it easier to communicate specific field validation issues. Here are the steps to customize validation error messages in Laravel.
- Define custom error messages:
You can define custom error messages inmessages()
your Form Request method or directly in the controller if you are validating fields in routes. Within this method, you should return an associative array where the keys represent the validation rules you want to customize and the values are the custom error messages. For example:
public function messages ()
{
return [
'name.required' => 'The name field is required.' ,
'email.required' => 'The email field is required.' ,
'age.min' => 'The minimum age allowed is 18 years.' ,
];
}
This will override the default error messages provided by Laravel for the specified validation rules.
- Placeholders in Messages:
You can add placeholders to custom error messages, which will be replaced with the actual values during validation. For example, if you want to include the minimum allowed age value in your error message:
public function messages ()
{
return [
'age.min' => 'Age must be at least :min years.' ,
];
}
The :min
will be replaced by the actual value defined in the validation rule.
- Multilingual Error Messages:
Laravel supports localization of error messages for multiple languages. You can define custom error messages for different languages by creating specific translation files. Laravel will automatically use the correct messages based on the language set in the application. - Validation on Routes:
If you are performing validation on routes or within your controller, you can customize the error messages directly on the route using the functionvalidate()
. For example:
Route::post( '/usuarios' , function (Request $request) {
$rules = [
'name' => 'required|string|max:255' ,
'email' => 'required|email|unique:usuarios' ,
];
$messages = [
'name.required' => 'Please fill in the name field.' ,
'email.email' => 'Please enter a valid email address.' ,
];
$request->validate($rules, $messages);
// If validation passes, continue processing the data.
});
Customizing error messages in Laravel is a valuable idea, as it makes your application communicate with the user in a clearer and more appropriate way. This not only improves the user experience, but also improves the overall quality of your application by making it easier to understand and resolve field validation issues. So feel free to get creative and make your messages more user-friendly.
Conclusion
In this post, we learned the importance of validation in Laravel to keep our data safe and ensure everything works as expected.
We saw how to define validation rules for fields and how to check if the data is correct. We also explored how to customize error messages to make the user experience more user-friendly.
Additionally, we discovered how to create Form Requests, an organized way to handle data validation while keeping our code clean and secure.
Customizing error messages is a great practice to make your application more user-friendly. This helps users understand and fix errors more easily.
Mastering validation is essential to building reliable applications. Use these tips to improve your skills and build stronger applications.
Deixe um comentário