KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

Laravel 5 Validation

Introduction

One of the advantages of using computers to processing data is elimination of errors. This doesn’t happen by accident. It is a deliberate effort of the developer.

For example, when processing an order, we expect the quantity input to be numeric. When signing up for an account, we expect the submitted email address to be unique in the users table. A password is expected to be a combination of lower and upper letters, special characters etc.

Validation allows us to check if the data submitted by the user follows the defined guidelines. In this tutorial, we will look at how we can take advantage of Laravel’s validation features to put constraints on the data before we process it.

By the time that you are done with this tutorial, your forms should be able to display validation error messages as shown in the image below

Laravel Validation

Topics to be covered

In this tutorial, we will cover the following topics

  • Tutorial prerequisites
  • Tutorial Starter Code
  • Server-side vs client-side validation
  • Laravel validation basics
  • Larashop Validation

Tutorial prerequisites

This tutorial assumes;

  • You understand the basics of Laravel 5. If you do then I recommend you start with these Laravel 5 Tutorial series.
  • You have PHP, MySQL and a web server i.e. Apache up and running
  • Laravel Homestead – this is optional but provides a great development environment. If you are new to Laravel homestead then I recommend you read the series on Laravel Homestead
  • You have composer installed
  • You have a text editor or IDE that supports PHP.
  • You have a modern web browser that supports HTML5
  • Git – this is optional but highly recommended. This tutorial has a repository on GitHub, with Git, you will be able to clone starter code for each tutorial.

Tutorial Starter Code

This tutorial builds on from the previous tutorial. If you have not been following the tutorial series, then you can download starter code for this tutorial from GitHub

If you have git installed, run the following command to clone the project

git clone -b 04_database https://github.com/KodeBlog/Laradmin.git laradmin

HERE,

  • git clone -b 04_database clones the branch laradmin from the repository https://github.com/KodeBlog/Laradmin.git into a local folder laradmin.

Server-side vs client-side validation

When it comes to validation, we have two major categories namely server-side and client-side validation. Most validation strategies usually involve using both techniques. Let’s start with server validation.

Server-side validation

As the name implies, server side validation is done on the server before the data is processed. A good example of server side validation is checking if a submitted user value i.e. email address is unique in the users table. If it is not, we return the message to the user email address is already taken.

The major drawback of server-side validation is performance. The client has to make a number of trips to the server back and forth.

The major advantage of server-side validation is we have complete control of the validation and we have some level of guarantee that the validation will always be performed assuming we have no bugs.

Client-side validation

As the name implies, client-side validation is done on the side of the user. The web browser usually using JavaScript/HTML5 performs the validation. For example, you can use the required attribute on a form input and the browser will ensure a value is entered before submitting the request.

The major advantage is this approach is better performance and bandwidth utilization. The application will make less traffic calls. The major disadvantage is when the user disables JavaScript in the web browser and you rely on JavaScript to perform client-side validation.

What validation technique should you use?

A combination of both server-side and client-side validation usually works best. For checks such as required fields, valid email address etc, you can take advantage of client-side validation to reduce network traffic.

However, you should user server-side validation as a fall back in case the user has turned off JavaScript and you cannot use it for validation. Certain checks such as checking if the email address is unique can only be done on the server-side. You can use Ajax to validate in real-time for such fields and display the feedback to the user without reloading the entire page.

Laravel validation basics

Laravel comes with validation functions out of the box. The framework does most of the heavy lifting for you. Let’s describe the validation flow and how the framework handles it.

Let’s say you have a controller called BrandsController. You will notice that the BrandsController extends the Controller class. If you check the definition of the Controller class in /app/Http/Controllers/Controller.php, you will notice that it uses the ValidatesRequest trait.

The trait will provide us with the validate method and we can use it as shown in the example code below.

public function store(Request $request)
{
    $this->validate($request, [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|unique:customers',
        'postal_address' => 'required',
        'physical_address' => 'required',
    ]);

    $customer = Customer::create([
        'first_name' => $request->input('first_name'),
        'last_name' => $request->input('last_name'),
        'email' => $request->input('email'),
        'postal_address' => $request->input('postal_address'),
        'physical_address' => $request->input('physical_address'),
    ]);

    return redirect()->route('customers.index')->with('success', "The customer <strong>$customer->first_name</strong> has successfully been created.");
}

HERE,

  • $this->validate($request, […]); calls the validate method and passes in the $request variable. The $request variable contains the data that is received from the user.
  • […] is an array of fields and validation rules. For example, 'first_name' => 'required', looks for a key first_name and checks to see if the user has submitted a value. Let’s have a look at a slightly complicated rule. Consider 'email' => 'required|unique:customers', this rules check to see if the email value has been submitted and looks into the customers table to see if the submitted email value already exists. If the email exists, then the validation fails. The pipe | is used to specify more than one rule. The above rule is perfect when creating a new record but what happens when updating the record? How do we validate the email address? We can write the rule as follows. 'email' => 'required|email|unique:customers,email,'.$id, the email field is required, must be a valid email address and should be unique in the customers table excluding the current record. So if you have admin@you.com in customers with an id of 1, the above validation rules checks the uniqueness of the email for all records except the one with id one.
  • return redirect()->route('customers.index')->with('success', "The customer <strong>$customer->first_name</strong> has successfully been updated."); redirects the client to the customers.index route and sets a session variable success with the value "the customer…". This message is displayed only once then discarded.

The official Laravel documentation has excellent examples and explanations on validation. You can read more by following this link Laravel validation.

Larashop Validation

In the previous tutorial, we looked at how to add records to the database but assumed the users will always submit values. We will continue with the previous example and add validation code to our controllers.

We will update the methods store (used to create new records) and update (used to update existing) records.

We already provided the code in the above example and explained the validation rules. For simplicity’s sake, the code for all the controllers will not be pasted in this tutorial.

You can attempt to write the validation code yourself then download the attached tutorial files to compare what you have written with what is in the tutorial files.

Complete Tutorial Code

The complete code for this tutorial can be cloned from the following branch

git clone -b 05_validation https://github.com/KodeBlog/Laradmin.git laradmin

Run the following command to browser to the root of the project

cd laradmin

We will now use composer to install dependencies.

composer install

When the installation is completed, run the following artisan command

php artisan serve

Summary

Laravel comes with validation out of the boxes and does most of the heavy lifting for you. A combination of both server-side and client-side validation provides the best strategy for validating user input.

What’s next?

The next tutorial will be Laravel 5 Eloquent Relationships. We will create the database for our admin panel using migrations and define the table relationship.

Kode Blog Tutorials is dedicated to bring you update to date, high quality free tutorials. You can support us by using the social media buttons to like and share the tutorial and subscribing to our newsletter. Please use the comments section below to give us feedback.

Each week, a new Laravel tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.