How to Add Form Validation in Laravel?

It is important to validate incoming data before allowing it to go through the framework and store it in the database. Laravel’s validator provides several rules that validate incoming data. These rules cover almost all data types and data formats for example integers, strings, float, email, etc.

There are two ways to validate incoming data in the Laravel framework which are following,

  1. Through Validator Facade
  2. Through Validator Request

Get Started

Before getting into details, let’s suppose we have clients and we need CRUD in the Laravel application to manage them. So we need to make sure that we need to create a controller, view, and route.

Create Controller

To create a controller run the below command into git bash or terminal,

php artisan make:controller ClientController –resource

This command creates a controller inside the app/Http/Controllers. –resource option creates resources in the controller which are seven methods index(), create(), store(), show(), edit(), update() and destroy(). In case you run a command without the –resource option, it would create an empty controller.

Create Blade File for View

In Laravel, views are the end files that get data from the controller and then display it into the browser with help of HTML and CSS. Also, it sends data to the controller through HTML forms and ajax requests. Laravel loads a view file from the controller and then displays data through it in the browser.

Laravel has a specific directory for views including CSS, JavaScript, and its libraries and localization. To create a view file go to resources/views and add a new file. Let’s create it,

create-client.blade.php

Create Route

The route provides a part of the URL that calls a method from the controller.  We need to create two routes, one would load the view file from the controller and another would send the request to the controller. Following are the routes,

Route::get('create-client', [ClientController::class, 'create']);

This route would call create() method from ClientController that would load the view.

Route::post('/store-client', [ClientController::class, 'store'])->name('store-client');

Above, the route would call the store() method with post request type.

Create HTML Form into Blade File

In the next step, we need to add the HTML form to create-client.blade.php view file.

<form method="post" action="{{ route('store') }}">
    @csrf
    <label>Client Name:</label>
    <input type="text" name="client_name"><br />
    <label>Client Email:</label>
    <input type="text" name="client_email"><br />
    <button type="submit" >Add Client</button>
</form>

In this HTML form, we added a route into the action attribute that would send the data to the store() method in ClientController. In the Laravel application, every HTML form should have @csrf. It generates a token for each session containing a random string that verifies if the authenticated user created the request.

Other than that, it has two inputs: the client name and email address.

Add Form Validation

We have created everything that is needed to add validation in the Laravel. In the next step, we need to add validation in the store() method from ClientController.

1. Through Validator Facade

Laravel does not include a validator facade into the controller by default. For adding the validator facade into the controller add the below code before class starts.

use Validator;

It imports the Validator class that has the make() method which takes requests and rules in arguments to validate the incoming data. Let’s add rules,

$rules = [
    'client_name' => 'required|string',
    'client_email' => 'required|email'
];

According to the first rule, the validator checks if the data with client_name is not empty and the data type is string otherwise it returns an error.

In the second rule, it checks if client_email has data and if it is an email address else it returns errors accordingly.

Next, we need to pass the $rules array into the validator make() method with the request.

$validator = Validator::make($request->all(), $rules);

The validator make() method validates incoming data by following rules and stores the response into the $validator variable. Now, we need an if-statement to handle validator errors.

if($validator->fails()){
    return response($validator->messages(), 200);
}

This if-statement checks the response of the validator fails() method, if it is true then it would return validator error messages into the response.

Conclusion:

In this tutorial, we have learned to add validation in Laravel and covered the following steps,

  • Validator introduction
  • Required files and routes to add validation
  • Create a controller with resources
  • Create a Blade file in the view directory
  • Create routes to load the form and send request
  • Add validation on incoming data through the validator facade.