Laravel Validation – The Step-by-Step Guide

Mastering Laravel validation is a step-by-step journey that involves understanding the intricacies of the framework. This article guides you through the process, providing insights into the essential steps for effective Laravel validation.

For those of you looking for an exceptionally flexible PHP framework that doesn’t take long to learn, and has a large community that can jump in with insight whenever you need it, then Laravel is your go-to. We’ve already dove into Laravel when discussing a Laravel vs Django approach. Now we’ll zoom in on Laravel validation, which is probably the function Laravel is most popular and best at for user input. In the following article, we’ll tackle validation in Laravel step by step. But first, let’s see what it is all about.

1. What is Laravel validation?

In short, you have an application, and you need to validate input data. The Laravel validator checks if that input respects your defined validation rules.

Laravel validation can be performed in several different ways, and the error messages are generated either automatically or manually, depending on the validate method of your choice. Once the input is validated, the rest goes as you would expect automatically. This way, you avoid further errors along the way.

2. How do I validate in Laravel?

We said there is more than one way to validate the input using Laravel.

You can use the Laravel request validate query parameter. This method is applicable right away on requests. When the Laravel validator fails, you are automatically redirected to the previous page. Same if the validation succeeds, it continues to the following step.

Another method is the form request. It is suitable for large input volumes, so your controller doesn’t get cluttered. Form request validation can also be performed in different ways: the rules() method, which is the easiest, and the authorize() method, which ensures the user has permission to submit the form. What is also great about the form request is that you can customize the validation error message for each form instead of instantly setting a message for the entire application.

A third validation method is the make() method, which implies manually creating validators. The downside is that you won’t enjoy the benefits of automation. But the good part is that you are free to handle custom error messages any way you like or need them.

Laravel Validation in 4 steps

Let us see the main steps to handle validation with the Laravel platform. Before we see the validation steps, you must define the routes and create the controller. You can use a PHP artisan make controller command to create the FormController.php file.

1. Writing The Validation Logic

With everything in place, you can now write the validation logic in the store method. For this, you can apply the validate method found in the Illuminate\Http\Request object, one of the Laravel validation array of objects. On validation failure, the framework generates an automatic response for the user, and you’ll see an Illuminate\Validation\ValidationException. If all is good, the execution continues normally.

Laravel validation stops on the first error. In some cases, stopping on the first validation error may be required for attributes value. For this, use the Laravel validation bail rule assigned to that attribute.

2. Displaying Validation Errors

You have defined the validation rules in Laravel, and the user input you receive does not comply. Laravel validation takes the user back to the previous page, and it does that automatically. The request input and validation errors are also automatically flashed to the session. If you apply the Illuminate\View\Middleware\ShareErrorsFromSession middleware, an $errors variable is shared to all the application’s views, so you know it is always defined. This Laravel validation variable can be found in the Illuminate\Support\MessageBag as an instance.

3. Form Request Validation In Laravel

Form Request validation is used for validation scenarios of increased complexity. These form request classes are custom classes with validation and authorization logic. To create the request class, run the PHP Artisan make:request command. The form request class generated this way is in the app/Http/Requests directory.

You can use type-hint if you require dependencies in the rule’s signature method. The service container resolves them automatically.

You can use type-hint if you require dependencies in the rule’s signature method. The service container resolves them automatically.

The good thing about this is that you don’t need to complicate your controller with validation logic. When you type-hint the request, the form request gets validated even before calling the controller method. As you can expect, the user is taken back to the previous location at the validation failure by an automatic redirect response. In the case of an XHR request, the user gets the 422 status code of the HTTP response with a validations errors’ JSON representation.

You may even “enrich” your form request with an “after” validation hook. The withValidator method can be used for that. Before Laravel evaluates the validation rules, you can call any methods, as a fully constructed validator is already received.

If you want to be sure that a certain user is authorized to update a resource, you can apply the authorize method available in this form request class.

To check the authenticated user’s information, you can run the user method, as the form requests extend the base Laravel request class. A false return of the authorize method is translated into a 403 status code, and there will be no execution of your controller method. Return true in the authorize method if you choose to handle authorization logic in other parts of the application.

4. Error Messages

Laravel provides a variety of methods to work with error messages. They are available in the Illuminate\Support\MessageBag instance, which you get in a validator instance when you call the errors method.

You can retrieve the first or all messages for a field (the first method or the get method). In the latter case, you may use the * character to retrieve all messages for each form field array.

With the all method you can retrieve, as you may expect, all the messages in all the fields. If you want to check if there is any error for a specific field, use the has method.

Custom Messages

If you have attributes that require custom messages, go to the lang/xx/validation.php language file of your application and add to the custom array the customizations you need. By default, Laravel has error messages in English, found in the lang/en/validation.php file. In this file, there are translation entries for each validation rule. It is possible to custom-translate the validation messages of the error to different languages by modifying the available translation entries.

To customize the error message in Laravel, you can use the Validator::make method and pass for the third argument your custom messages. The “dot” notation is used for a specific field. First, write the names of the attributes, then the custom rules.

3. Available Validation Rules in Laravel

One of the advantages of Laravel validation rules is that they are already there, ready to be picked up and used if your application does not require particular customization.

While Laravel 8 validation rules counted around 70, Laravel 9 currently has over 80 validation rules, which will make your life a lot easier.

Let’s go through some of the most common.

accepted

Every website and application has that field that needs to be checked (although few people do read and agree on it) – the Terms of Services or Terms and Conditions. It has to be accepted for the user to proceed on the website or application. You have the accepted validation rule with the values yes, on, 1, or true.

array

You may need to validate entire field arrays to use the Laravel validation for the array, provided the field under validation is a PHP array.

after:date, after_or_equal:date or before:date and before_or_equal:date

These rules commonly validate dates, provided that date has to be a PHP strtotime function.

confirmed

It is popular for password confirmation, requiring a matching foo_confirmation field. We’ll explain it further in the article.

email, ip, active_url

These rules ensure the input is valid by checking the fields against certain patterns.

exists:table, column and unique:table,column

This rule is useful to validate fields in given databases.

required

This rule validates that a field provided is not empty. For a field to be considered empty, several value conditions must pass as true:

  • The value of the field is a no path file.
  • The array or Countable object is an empty value
  • There is an empty string
  • You have a null value.

Other variations for the required rule add conditions for the fields under validation.

4. What is custom validation in Laravel?

Image from undraw.co

Laravel is great for fast web app development with its wide range of already available validation rules. However, sometimes custom software development requires custom validation rules. Just as it was possible to set custom error messages, extending the set of built-in validation rules with your own customized ones is possible.

Those who have worked with Laravel 5 validation may remember the Validator::extend method. By doing so, three parameters were sent to the custom validator Closure: $attribute, its $value, and the rule’s $parameters. Instead of using Closure to extend the Validator, you could extend the Validator class using Illuminate\Validation\Validator. More validation methods could be added by using the validate prefix. When error messages needed custom place-holder replacements, you could add a replaceXXX function to define them.

Fast forward to Laravel 9 validation. There are two ways to add to the Laravel validation rules array: by using rules objects or closures. Let’s see when to use each of them.

Rule Objects

In the PHP Artisan makecontroller, write the make:rule command. The rule goes into the app/Rules directory. This directory may already exist, or it can be created upon the execution of the Artisan commands.

To define the rule’s behavior, pass a rule object instance with the other validation rules to attach it to a validator. The rule object has one method, invoke, which gets the attribute name, the value, and what to invoke in case of failure. Laravel can also translate an error message on the $fail closure by providing a translation string key.

Suppose additional data undergoes validation, and you need to access it with custom validation. In that case, the Illuminate\Contracts\Validation\DataAwareRule interface may be implemented by the rule class, for which you need a setData method. Laravel 9 will automatically invoke this method for all data submitted for validation. Moreover, to access the instance that performs the validation, use the ValidatorAwareRule interface.

Closures

If the application requires a custom validation rule only once, then closure is a better way to apply it. The closure gets the attribute name, the value, and the $fail callback for the validation failure.

Implicit Rules

When attributes are empty, neither custom rules nor built-in validation rules are run. To ensure a custom rule is run despite an attribute’s empty string, create an “implicit” rule by applying the Illuminate\Contracts\Validation\ImplicitRule interface. You won’t need to implement additional methods because the interface acts as a validator’s “marker interface.”

A new implicit rule object can be created with the Artisan command make: rule and the –implicit option.

5. What is confirmed in Laravel validation?

As mentioned, confirmed is one of Laravel’s built-in validation rules. It implies that to be validated, the field has to have a {field}confirmation correspondent in the input. The most common use case for confirmed in Laravel is confirming a password. Following their guidelines, you should implement a password_confirmation field in the request for the validation rule to find and check the equality.

Another way to confirm a password is to use the same:password rule for the password_confirmation field check.

With the Laravel validation rules array of over 80 and the possibility to build custom validation rules and custom error messages in a rather easy manner, no wonder that in 2021, it was considered one of the best web development frameworks. It is safe to say that the current Laravel 9 version can easily stay on top as one of the most used frameworks, at least when it comes to validation.

Related post

Upcoming resource:
Pre-register to get early access to a comprehensive audit and in-depth analysis of 25 HCP portals across Europe.

Ready to start your web project?

Blending technology with creativity, Teodora turns cups of coffee into carefully written thoughts. With the power of the Oxford comma and a bit of magic, she brings words closer to people.

hello@digitalya.co

Articles
Browse more related content

#Development Tools

Vue Js Methods – Demystified

#Development Tools

Vue vs Angular – A comprehensive comparison

#Development Tools

PHP vs Node — a head to head comparison

#Company Culture

Building a different kind of company — Digitalya’s 10-year journey

#Healthcare

Building a nurse education platform — key features

#Healthcare

Using GenAI for personalized HCP engagement

Do you want to develop a product?

Validate your business with real users