Laravel 5 Middleware Tutorial With An Example

Laravel 5 Middleware Tutorial example is today’s main topic. One of the primary requirement of any web application is HTTP request filtering, and we all need to implement that functionality very well. Laravel PHP Framework provides that functionality also and this concept is called as “Laravel Middleware.” 

If you want to know the really basic CRUD Functionality in Laravel 5.4, then check out my article Laravel 5.4 Crud Example From Scratch

Middleware

As its name suggests, we need to implement some functionality during the request hit on the particular URI. It is like layers; we need to put in between our request and response. Laravel 5 middleware provides us very flexible API to do that, and we can also implement our custom middleware with in no time. Just need to fire one command and Laravel all set up. We just need to write logic in the particular function and define that in our application. That is it, Folks. Okay so let’s deep dive into it with some of the examples.

Step 1: Create a project Laravel 5 Middleware Tutorial.

 Type the following command in your CMD.

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

Go to phpMyAdmin and create one database called laravel middleware. You can name it anything.

Switch to your editor and edit .env file and put your database credentials in it.

Step: 2 Laravel 5 Admin Middleware.

Now, To checking that if the current user is administrator or not. So go to your users’ table migration file and add one more field called isAdmin and its data type is boolean.

<?php

// create_users_migrations

  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();
        });
    }

Now run the following command.

php artisan migrate

Next step is to create Authentication functionality provided by Laravel. So type following in your terminal.

Laravel 5.4 Authentication.

php artisan make:auth

So auth scaffold will generate successfully.

Start the server by typing following command.

php artisan serve

Now create three users. So go to the following URL: http://localhost:8000/register

Right now, we have not assigned any users to admin, but we can do it manually. Remember, in the real time web application; you need to provide some interface to give administrative rights. In here I am just showcasing you that, how you can deal with admin middleware after sign in the form.

So assign any user’s isAdmin field to value one manually in the database.

Step 3: Make one basic Laravel Middleware.

Create one middleware by typing following Laravel Command.

php artisan make:middleware Admin

Navigate to the following directory.  app  >>  Http  >>  Middleware  >>  Admin.php

You can see there is some boilerplate provided by Laravel.  There is mainly one function you have to deal with, and that is handle()

// Middleware Admin.php

  /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }




We need to write logic in this function so that we can filter the request and if it satisfies then go to destination page otherwise back to login or whatever redirect page, you will provide.

I am writing one logic in this function.

  /**  Admin.php
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if(auth()->user()->isAdmin == 1){
        return $next($request);
      }
        return redirect('home')->with('error','You have not admin access');
    }

Now, I need to register this route in app  >>  Http  >>  Kernel.php

You can register this route in two separate ways.

  1. You can register as a global middleware.
  2. You can register as a particular route called route middleware.

We are registering as a route middleware so, go to the protected $routeMiddleware property.

<?php

// Kernel.php

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\Admin::class,
    ];

Here as you can see, I have added our custom middleware called admin.

Read More
1 of 4

Now, if we want to assign any route to this middleware admin then this routes now protected and only accessible when authorized user is admin otherwise it will redirect to the home page.

Step 4: Admin protected route middleware

Create one route, which needs to be admin protected, and if the user is not an admin, then it will redirect to the home page otherwise he can access this page.

<?php

// web.php

Route::get('admin/routes', 'HomeController@admin')->middleware('admin');

Now, we just need to put this link on the home page after the user has signed in.

<!-- home.blade.php -->

@extends('layouts.app')

@section('content')
<div class="container">
  @if(\Session::has('error'))
    <div class="alert alert-danger">
      {{\Session::get('error')}}
    </div>
  @endif
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    <a href="{{url('admin/routes')}}">Admin</a>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, all we need is to code the admin function resides in HomeController.

<?php

// HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    public function admin()
    {
        return view('admin');
    }

}



Step 5: Make one blade file.

Create one view called admin.blade.php in the root of the views folder.

<!-- admin.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ADMIN PAGE</title>
  </head>
  <body>
    WELCOME TO ADMIN ROUTE
  </body>
</html>

Now, go to login page  and logged in with the isAdmin field 1

Here is my login page of Laravel 5.4

Laravel 5 middleware tutorial

 

After logging in this is how my screen looks like this.

Laravel 5.4 Middleware

 

You are logged in as an admin so; you can see the following page.

If you are logged in as a regular user then, you will redirect to the same page like in our case it’s a home page with the following error.

Laravel Route Middleware

Laravel 5 Group Middleware

<?php

// web.php

Route::group(['middleware' => ['admin']], function () {
    Route::get('admin/routes', 'HomeController@admin');
});

We can use middleware groups to assign one middleware to multiple routes. It is very easy.

If I do not want to show the Admin links to the normal user, then I have put a condition like if authenticate the user is an admin then and then we can show him that route otherwise not. But in this example, I have not put anything like that.

I just want to show you that if you are not admin and still you will try to access this route, then you will redirect with a proper message.

Multiple Middlewares in Single Route

We can put two middlewares into one route at a time.

Route::get('admin/routes', 'HomeController@admin')->middleware(['admin','auth']);

Auth Middleware Provided By Laravel

<?php

// Kernel.php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

auth and guest middlewares are related to Authentication of the User.

VerifyCSRFToken is the another middleware, which is global middleware and protects us from Cross Site Request Forgery attack in every POST request.

That TokenMismatchException is thrown by this middleware if POST request does not contain CSRF Token.

That is it for Laravel Middleware Tutorial.

Github: https://github.com/KrunalLathiya/Middleware

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to the root of the project and run command “composer update.“
  3. Edit .env file and use your MySQL database credentials.
  4. Add one admin field in the user’s table.
  5. Run the command “php artisan migrate.“
  6. Now, we need to bootstrap Laravel server so run “php artisan serve.“
  7. If now go to this URL: http://localhost:8000/register and create three new users and change one of the user’s admin value to one
  8. Now logged in like three different users and click the admin link in the home page, If the middleware is applied by you in that link’s route then it will work as I have described above.

If you still have any doubt in this Laravel Middleware Tutorial Example then ask in a comment below.

You might also like More from author

Leave A Reply

Your email address will not be published.