How to use Laravel Middleware with an example

In this tutorial, we will learn about laravel middleware with an example. Question is why do we need middleware? what is the use of middleware? or What is middleware? well, In almost every application we need middleware to filter the HTTP request. For example, Let's say you want to protect your class function or you want to protect your routes in such that only logged in user can access the routes.
Laravel provides the functionality to do so, and this concept is known as "Laravel Middleware".

If you want to learn about how to install the latest Laravel project, You can follow the below link.
Install Laravel on ubuntu 18.04

Create a Laravel project.

For this tutorial, we will create a new project to implement the Laravel middleware example. To install Laravel latest project Type the following command.

composer create-project laravel/laravel middlewareExample --prefer-dist

In the above command create a new project with middlewareExample the name.
Now create a database for this project. You can create with PHPMyAdmin or by login MySQL using the terminal. Once you are done with creating a database. Open the installed project and update database configuration in the .env file with the following code.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db_name
DB_USERNAME=root
DB_PASSWORD=root

Laravel Authentication

To enable auth in Laravel 6 you will need to install the Laravel UI package. To do so enter the following command.

composer require laravel/ui

The above command will install the Laravel UI package. Now enter the following command to enable Laravel 6 Authentication

// Generate basic scaffolding...
php artisan ui bootstrap

// Generate login / registration scaffolding...
php artisan ui bootstrap --auth

Update User Migration File

Update the user migration file with the following code which can be located in database/migrations/2014_10_12_000000_create_users_table.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->boolean('isAdmin')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

In the above code, we have added one extra field isAdmin which we will use to identify if the logged-in user is admin or not.

After updating the file. Run the following code to migrate the database.

php artisan migrate

Now run the application with the following command.

php artisan serve

Now register a new user and set isAdmin to 1.

Create Laravel 6 middleware

Enter the following command to create a new middleware

php artisan make:middleware AdminMiddleware

The above command will generate new AdminMiddleware in app\Http\Middeware\AdminMiddleware.php. Now update the following code in admin middleware to check if the user is admin or not.

public function handle($request, Closure $next)
{
    if (!auth()->user()->isAdmin == 1) {
        return redirect('home')->with('error', 'Failed to log in as admin');
    }

    return $next($request);
}

There are two options to call the middleware.

  1. Global middleware
  2. Route based middleware

Register middleware as global

To register middleware as globally update the app\Http\Kernel.php with the following code.

protected $routeMiddleware = [
    .......
    'permission' => \App\Http\Middleware\PermissionMiddleware::class,
    'verifyApiKey' => \App\Http\Middleware\ApiMiddleware::class,
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

Applying Admin middleware on Routes

There are two ways to apply middleware on routes.

  1. Middleware on single Route
  2. Middleware on a group of Routes

Middleware on single Routes

Laravel provides middleware method to apply middleware on single routes. Below is the example of middleware on single routes

Route::get('admin/dashboard', 'AdminController@index')->middleware('admin');

Middleware on a group of Routes

Laravel provides route groups to apply multiple functions. Below is the example to apply middleware on the route using Laravel Route group

Route::group(['middleware' => ['admin']], function () {
    Route::get('admin/dashboard', 'AdminController@index');
    Route::get('admin/profile', 'AdminController@profile');
});

 Laravel will apply admin middleware on all routes which are in the Route.