Forms and Validation in Laravel

Tram Ho

1. Form

First, we need to learn the ways to secure forms in Laravel. To secure forms in Laravel, you can use several ways as follows:

  • Use CSRF token: CSRF stands for Cross-Site Request Forgery , which is an attack method where an attacker can forge a request from a user to a web application. Laravel provides CSRF token to solve this problem. You can use the @csrf directive to add a CSRF token to your form.

  • Use HTTPS: HTTPS is a protocol that secures and encrypts data on the network. Using HTTPS will help prevent attackers from forging user requests.
  • Use validation: Laravel provides validation rules to check the data sent by the user. You should check your inputs to make sure they are not hacked.

Above are some ways to secure forms in Laravel. However, this is only part of securing your web application. You should learn more about web security to ensure that your application is secure and free from attacks.

2. Validation

Validation for what?

Validation is used to check the validity of data entered by the user before processing the data or saving it in the database. It helps ensure that imported data meets predefined requirements and constraints, helps avoid unexpected data errors, and increases application security.

Here is a simple example of validation in a Laravel controller:

  • In this example, we define a store() function to handle the user registration request. First, we use the Validator::make() function to create a validator object and pass in the registration data sent from the user and the validation rules.
  • In this case, we are checking to see if the “name” field is required, cannot exceed 255 characters, the “email” field is in the correct email format, there are no duplicates in the database, and can be more than 255 characters, and the “password” field is mandatory, cannot be shorter than 6 characters, and cannot exceed 255 characters.
  • If the validator detects that the data is invalid, it returns a $validator object with specific error messages. We use the withErrors() method to pass this validator object to the registration view so that the user can see where his error is and can correct the data. We also use the withInput() method to retain the user entered values ​​on the form.
  • If the data is valid, we save the user data in the database and redirect the user to the login page.

Looking at the above we see that this Controller seems to be taking on a lot of work, with simple logic handling we already have to spend quite a few lines of code, if the logic is complicated with more validation, the code will really messed up. This is where we need the Form Request .

Create Form Request

We can create FormRequest via artisan command:

This command will create for us the StoreBlogPostRequest file at AppHttpRequests. This file includes two default methods, authorize() and rules().

In this example, we have created a Form Request StoreBlogPostRequest with two fields title and body. The rules() method defines the validation rules that apply to these fields.

However, in some cases, we may want to add rules or check additional data after validation. For example, check if an email already exists in the database, or add some complicated condition to check the validity of the data. To do this, we can use the withValidator() method. . This method takes a Validator object as a parameter and allows us to add rules or check additional data.

Here, we used the after() method of the validator to add a closure to check if the email already exists in the database after the data is validated. If there is an error, we will add the error to the validator using the add() method of the validator. If there is no error, the next logic will be executed in the Controller.

Then you can use the Form Request in the Controller like so:

In the above code, we have used the Form Request StoreBlogPostRequest in the store() method of the BlogController Controller. This will help Laravel automatically execute the validation rules and return the corresponding error messages if the data is invalid. If the data is valid, we can continue to process the data in the store() method.

To display the validation error message, you can use the messages() method in the Form Request or the validate() method in the controller. If you use the messages() method in the Form Request, you can define custom error messages for each validation rule.

For example, to define the error message in the example above, we could modify the rules() method as follows:

In this example, we have customized the error messages for each validation rule. For example, if the user does not enter a title, Laravel will return the error message “Please enter a title” instead of “The title field is required.” default.

How to display error in view after validation?

To display validation error messages in the view, you can use the $errors variable. This variable is an instance of the IlluminateSupportMessageBag class and contains the validation error messages.

In the view, you can use the has() method to check if the $errors variable contains an error message. If so, you can use the first() method to get the first error message. For example:

Here, we use the has(‘title’) method to check if there is an error message for the title field. If so, we display the first error message for this field using the first(‘title’) method.

Thank you for reading, hope the article can be useful

Reference source:

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo