Laravel Validation

Laravel Validation: Comprehensive Guide, part 1

Introduction

In this tutorial I’ll cover different ways you can validate your data in Laravel 4. Almost every interactive web application requires some kind of data validation. For example, if your web application have registration form, you want email field to be unique or require from users to confirm their password. Laravel already has many standard rules to use within your validator, but if you don’t find one that meets your requirements at any time you can create your own rule.

There is a many ways how you can implement validation and I think the most common and the easiest way is to validate data directly in your controller. But, before we start validating our data let’s configure database and create migration for our  users table.

What we are building?

To see Laravel validation in action we will create simple user registration form. On that registration form we’ll apply the following rules:

  • First name – required, alpha only, maximum 100 chars
  • Last name – required, alpha only, maximum 100 chars
  • Email – required, check is correct email format
  • Password – required, alpha-numeric, confirmed, minimum 8 characters, must be confirmed

And here is how our simple form will look like:

Laravel Validation

Database, migrations, routing…

You need to set your database configuration in the app/config/local/database.php , I’ll use homestead’s default settings for this example:

Users table will contain only four fields: first_name, last_name, email and password. To create migration run artisan  migrate:make command:

this command will create a new migration file in the  app/database/migrations folder. Open that file and change up method as follows:

After you have updated migration file you need to run artisan  migrate  command:

Result of the migrate command is:

In the next steps we will define two routes, one for get and another one for the post requests, and we’ll make basic form view for these routes.

Basic Eloquent Model

Before creating routes and views, let’s establish our User model. Model contains all Business Logic of your application, which means it describes how the application interacts with the database. Laravel comes with simple and elegant  ActiveRecord implementation called Eloquent ORM which makes this interaction incredibly easy.

Here is a simple User model we’ll use for this example:

By default Eloquent models are protected against mass-assignments. For this reason in  $fillable  property we can white list attributes we want to  be mass-assignable.

Setting up Routes

As I said before, we’ll need only two routes. One will handle  GET  requests, and another one will handle  POST  requests:

You can access this at http://homestead.dev/users/registration. As you can see,  POST  request will be send to the same URL.

Now when the routes are set, let’s set up basic form view.

Create Form View

You already know that Laravel store views in  app/views  folder. So create new view called app/views/users/registration.blade.php :

I’ll assume that you already have some basic understanding of the Blade templating engine. You also need to create default layout; just paste this code in app/views/layouts/default.blade.php :

After creating our model, setting up routes and basic view, we can switch our focus to the main topic of this article – validation.

Validation

Laravel provides a great validation system, full of functionalities intended to help you validate your data. The Validator class is responsible for all of that. Simplest way to use Validator class is by calling  Validator::make()  method. This method has four arguments. The first argument is an array of data to validate, second is an array of rules, third argument is an array of validation messages and fourth argument is an array of custom attributes.

The Validator class also has some useful methods you can use. I’ll mention some of them:

To see other functionalities of this class you should visit the API documentation page.

Controller level validation

NOTE: To much code inside controllers can make them difficult for testing and maintaining. You should keep your controller skinny, avoid putting everything inside it as much is possible. Follow SOLID principles.

Almost every book I read about Laravel development covers this type of validation. Because it’s fairly easy to implement it’s preferable for small applications. But for larger applications I recommend putting validation logic outside the controller.

Here is an basic example of data validation:

The first argument we passed to the  make  method represent data under validation. The second argument are the validation rules we want to apply to the data.

If you want to provide custom messages, just pass them as third argument of the  make  method, like this:

By default Laravel will take attributes from data array you provided. As I have already mentioned, make  method have four parameters. The fourth parameter is used to customize attribute display in validation messages. This is very useful when you want to localize your application. To take an advantage of this feature let’s see how localized application would look like. First you need to modify $messages array to get localized messages:

next, create an language file for the registration form app/lang/{locale}/registration.php , in this case I’ll put Bosnian localization in app/lang/bs/registration.php :

And we need to update our store  method a little bit:

As you might guess, if you try to submit the form everything will work fine, same as before. The only difference is that we get localized version of the error messages:

laravel_validation_localized_messages

Can you see the problem in the image above? Laravel didn’t translate attribute fields, because we haven’t specify them anywhere. Fortunately, we have a possibility to set custom attributes by providing the fourth argument to the  make  method:

Don’t forget to create app/lang/{locale}/attributes.php :

Now when you try to submit the form you should have localized error messages as well as attributes:

Laravel localization

Another way to set custom attributes is by using setAttributeNames  method on a Validator instance:

And that’s it. Now you know how you can perform simple validation, localize your error messages and set custom attributes. In the next article, I’ll cover model and service level data validation.

If you have any comments or suggestion how to improve this article, feel free to leave a comment below.

 

 

Follow me

Mirza Pasic

Full Stack Developer at OLX
Web Developer. Geek. Systematic. Dreamer
Follow me

Published by

Mirza Pasic

Web Developer. Geek. Systematic. Dreamer