• Reading time ~ 4 min
  • 08.09.2023

Today's post is again a little bit about the obvious thing, data validation. Why you need validation, how to use it, custom rules, and why you need to use a Form Request for validation.

If we talk about the projects that I came across on freelancing, very often receiving data from a user looked like this: What is the problem? With such receipt of data from the user, the developer opens up the possibility of carrying out two types of attacks on his application:

  1. XSS (Cross-Site Scripting — «міжсайтовий скриптинг») — досить поширена вразливість, яку можна виявити в багатьох веб-додатках. Її суть досить проста, зловмиснику вдається впровадити на сторінку JavaScript-код, який не було передбачено розробниками.
  2. SQL-ін'єкція (SQL-injection) - це вразливість веб-безпеки, яка дозволяє зловмиснику втручатися в запити, які додаток робить до своєї бази даних. Як правило, це дозволяє переглядати дані, які він зазвичай не може отримати. Це можуть бути інші користувачі, або будь-які інші дані, доступ до яких має сам додаток. У багатьох випадках зловмисник може змінювати або видаляти ці дані, викликаючи постійні зміни у вмісті або поведінці програми.

So, first of all, validation is aimed at ensuring the security of data in the application, and secondly, validation guarantees the correctness of the data, entered by the user, and helps to avoid incorrect data in the database.

There are several ways to validate data in Laravel:

  1. Використання методу validate який реалізований в трейті ValidatesRequests. За замовчуванням усі контролери, які розширюють базовий контролер наслідують цей трейт. Сам метод validate  приймає в себе об'єкт класу Illuminate\Http\Request, масив правил для валідації полів, масив з кастомними меседжами для виводу помилок, та масив з кастомними атрибутами останні два не є обов'язковими. Тому виконати валідацію даних можливо одразу в контролері, засобами самого контролела і виглядає це так:

2. It is also possible to use the method of the Illuminate\Http\Request class itself, which takes almost the same data as in the previous example, with the exception of the object $requestof the validate class .

3. Another way to validate is to create a validator manually using the Illuminate\Validation\Validator façade and its methodmake. The first argument passed to the makemethod receives the data to be tested. The second argument is the validation rules that should be applied to the data.

4. In my opinion, this method is the most correct from an architectural point of view. The use of validation through a separate class that implements the Form Request allows you to solve one of the main principles of SOLID - the Single Responsibility Principle. Laravel already has an implemented command to create the Form Request:php artisan make:

request NewValidationRequest class

This command will create the next class in app/Http/Requests, by default the class is created with two methods authorize and rules. The method allows you to implement the logic of checking whether the user has the necessary permissions to execute the request. If it returns, the query will continue to the method authorize rules for validation. If authorize authorize it returnstruefalse, the user will be redirected to the error page or processed according to the specified custom logic. Method rules stores and returns an array of rules against which the input data will be checked. This class can be extended by messages implementing methods and , which in turn will return custom messages for validation errors, and attributescustom names for attributions.

It is possible to get clean data in the controller when using the Form Request class in the same way as when using a regular validator of the Request:

I will not copy-paste class, and list all available rules for validation. The official documentation describes all possible rules https://laravel.com/docs/10.x/validation#available-validation-rules, but if these rules aren't enough to cover all of your fields, Laravel has a mechanism to create your own custom validation rules.

This mechanism allows you to create your own validation rules that meet the specific needs of your application. To create a new rule, use the command:php artisan make:

rule CustomValidationRule

It creates a new rule in the app/Rules folder, and the class itself implements only 2 methodspasses, which should contain the logic by which the field will be checked and message which stores the message when the data is invalid.

In order to use this rule in validation, it is enough to add it to the rule array:There are also several ways to receive and handle errors, depending on the option by which the data is validated. If you need to get errors when using the Validator class, then all errors can be obtained by referring to errorsthe :And if an object of the Request class was used for validation, then you can get errors from the session:

In the case when you need to handle errors in blade files, a $errors global variable is inserted there, which automatically becomes available for all layouts, and is also an instance of the MessageBag class.

Приклад виводу всіх помилок в циклі

Or, if you need to display a specific error, for example, a helper directive is used for one field@error

Приклад виводу однієї вибранох помилки


No comments yet
Yurij Finiv

Yurij Finiv

Full stack


Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
Ukraine, Lutsk