For those of you looking for a PHP framework that is exceptionally flexible, 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, for user input, is probably the function Laravel is best known for and best at. 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? 2. How do I validate in Laravel? 3. Available Validation Rules in Laravel 4. What is custom validation in Laravel? 5. What is confirmed in Laravel validation?

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 the validation rules you had defined.

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 expected, automatically. This way you avoid further errors along the way.

2. How do I validate in Laravel?

Right, 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 can be applied 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 makes sure the user has permission to submit the form. What is also great about the form request, is that you can also 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, of course. 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 which are the main steps to handle validation with the Laravel platform. Before we see the actual validation steps, you need to first 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. What Laravel validation does is take 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 of their own. To create the request class, run the PHP Artisan make:request command. The form request class generated this way can be found 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 having called the controller method. As you can expect, at the failure of validation, the user is taken back to the previous location by an automatically 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 are able to call any methods, as a fully constructed validator is already received.

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

To check the information of the authenticated user, you can run the user method, as the base Laravel request class is extended by the form requests. 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 comes with error messages in English, which are 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.

Avatar

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 has currently 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 actually agree on it) – the Terms of Services or Terms and Conditions. It has to be accepted in order for the user to proceed on the website or application. Well, you have the accepted validation rule for that with the values yes, on, 1, or true.

array

You may need to validate entire field arrays so you can 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 are common to validate dates, provided that date has to be a PHP strtotime function.

confirmed

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

email, ip, active_url

These rules make sure that the input is valid, by checking the fields against certain patterns.

exists:table, column and unique:table,column

This rule is used to validate fields in given databases.

required

This rule validates a field provided is not empty. For a field to be considered empty, there are several value conditions that 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.

There are other variations for the required rule that adds 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, it is also possible to extend the set of built-in validation rules with your own customized ones.

Those of you 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 by 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, presently, two ways to add to the Laravel validation rules array: by using rules objects or by using 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 in 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 get it attached 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.

If there is additional data that undergoes validation and you need to access it with custom validation, 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 the use of a custom validation rule only once, then using 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 the builtin validation rules are run. To make sure a custom rule is run despite the empty string of an attribute, create what is called 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 we’ve already mentioned, confirmed is one of Laravel’s built-in validation rules. It implies that in order 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. For this, 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.

Custom Software
Development
Do you have a Laravel
project in mind?
Contact us