What is Middleware?

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middleware directory.


Middleware acts as a middle man between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.

Middleware can be created by executing the following command −

php artisan make:middleware <middleware-name>

Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

To create a new middleware, use the make:middleware Artisan command:
php artisan make:middleware AgeMiddleware
This command will place a new AgeMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200. Otherwise, we will redirect the users back to the "home" URI.

Example
Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −

php artisan make:middleware AgeMiddleware
Step 2 − After successful execution of the command, you will receive the following output −

AgeMiddleware
Step 3 − AgeMiddlware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.

<?php
namespace App\Http\Middleware;
use Closure;

class AgeMiddleware {
public function handle($request, Closure $next) {
return $next($request);
}
}

Defining Middleware :-

To create a new middleware, use the make:middleware Artisan command: php artisan make:middleware AgeMiddleware This command will place a new AgeMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200. Otherwise, we will redirect the users back to the "home" URI.

<?php

namespace App\Http\Middleware;

use Closure;

class AgeMiddleware
{
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('age') <= 200) {
return redirect('home');
}

return $next($request);
}

}

if the given age is less than or equal to 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the $next callback with the $request.

Before / After Middleware :-

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// Perform action

return $next($request);
}
}

However, this middleware would perform its task after the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);

// Perform action

return $response;
}
}


Registering Middleware :-

There are two types of Middleware in Laravel.

  • Global Middleware
  • Route Middleware
  • If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

    Assigning Middleware To Routes :-

    If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:

    To register the global middleware, list the class at the end of $middleware property.

    protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    // Within App\Http\Kernel Class...

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

    Once the middleware has been defined in the HTTP kernel, you may use the middleware key in the route options array:

    Route::get('admin/profile', ['middleware' => 'auth', function () {
    //
    }]);
    Use an array to assign multiple middleware to the route:

    Route::get('/', ['middleware' => ['first', 'second'], function () {
    //
    }]);

    Instead of using an array, you may also chain the middleware method onto the route definition:

    Route::get('/', function () {
    //
    })->middleware(['first', 'second']);
    When assigning middleware, you may also pass the fully qualified class name:

    use App\Http\Middleware\FooMiddleware;

    Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {
    //
    }]);

    We can now register it in route specific middleware property. The code for that registration is shown below.

    The following is the code for app/Http/Kernel.php

    <?php
    namespace App\Http;
    use Illuminate\Foundation\Http\Kernel as HttpKernel;

    class Kernel extends HttpKernel {
    protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'Age' => \App\Http\Middlware\AgeMiddleware::class,
    ];
    }


    Middleware Parameters :-

    We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.

    public function handle($request, Closure $next) {
    return $next($request);
    }



    Example
    Step 1 − Create RoleMiddleware by executing the following command −

    php artisan make:middleware RoleMiddleware
    Step 2 − After successful execution, you will receive the following output

    Middleware Parameters
    Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.

    <?php
    namespace App\Http\Middleware;
    use Closure;

    class RoleMiddleware {
    public function handle($request, Closure $next, $role) {
    echo "Role: ".$role;
    return $next($request);
    }
    }
    Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.

    RoleMiddleware
    Step 5 − Execute the following command to create TestController −

    php artisan make:controller TestController --plain
    Step 6 − After successful execution, you will receive the following output −

    TestController
    Step 7 − Copy the following code to app/Http/TestController.php file.

    app/Http/TestController.php

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;

    class TestController extends Controller {
    public function index(){
    echo "<br>Test Controller.";
    }
    }
    Step 8 − Add the following line of code in app/Http/routes.php file.

    app/Http/routes.php

    Route::get('role',[
    'middleware' => 'Role:editor',
    'uses' => 'TestController@index',
    ]);
    Step 9 − Visit the following URL to test the Middleware with parameters

    http://localhost:8000/role

    Step 10 − The output will appear as shown in the following image.



    Terminable Middleware :-

    Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with “terminate” method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.


    Example
    Step 1 − Create TerminateMiddleware by executing the below command.

    php artisan make:middleware TerminateMiddleware
    Step 2 − This will produce the following output −

    Terminable Middleware
    Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.

    <?php
    namespace App\Http\Middleware;
    use Closure;

    class TerminateMiddleware {
    public function handle($request, Closure $next) {
    echo "Executing statements of handle method of TerminateMiddleware.";
    return $next($request);
    }

    public function terminate($request, $response){
    echo "<br>Executing statements of terminate method of TerminateMiddleware.";
    }
    }
    Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware.

    TerminateMiddleware
    Step 5 − Execute the following command to create ABCController.

    php artisan make:controller ABCController --plain
    Step 6 − After successful execution of the URL, you will receive the following output −

    ABCController
    Step 7 − Copy the following code to app/Http/ABCController.php file.

    app/Http/ABCController.php

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;

    class ABCController extends Controller {
    public function index(){
    echo "<br>ABC Controller.";
    }
    }
    Step 8 − Add the following line of code in app/Http/routes.php file.

    app/Http/routes.php

    Route::get('terminate',[
    'middleware' => 'terminate',
    'uses' => 'ABCController@index',
    ]);
    Step 9 − Visit the following URL to test the Terminable Middleware.

    http://localhost:8000/terminate

    Step 10 − The output will appear as shown in the following image.

    File name : index.php


    How to create custom MiddleWare

    Middleware are the easiest way of verifying HTTP requests before they are passed to the controller. All middleware in Laravel are created in the Middleware folder, located inside the `app/Http/Middleware` folder.

    php artisan make:middleware ItechxpertMiddleware

    <?php

    namespace App\Http\Middleware;

    use Closure;

    class ItechxpertMiddleware
    {

    public function handle($request, Closure $next)
    {

    $arr = [
    'Bihar',
    'Jharkhand',
    'Delhi',
    'Up'
    ];
    if(in_array($request->state,$arr)){
    dd("{$request->state} is available in this array");
    }
    return $next($request);
    }
    }

    Step 2: Create Route

    File name : route.php

    Route::get('/test', 'HomeController@test');

    Step 3: Add Controller Method

    File name : index.php

    php artisan make:controller HomeController

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Http\Middleware\ItechxpertMiddleware;

    class HomeController extends Controller
    {
    public function __construct()
    {
    $this->middleware(ItechxpertMiddleware::class); //Our Middleware
    }

    public function test()
    {
    return "Hello Itechxpert";
    }
    }

    Run this url

    localhost/laraweb/test?state=Delhi


    output :- Delhi is available in this array

    Step 4 : Register Middleware

    File name : kernel.php

    use middleware inside our controller to call our custom middleware class inside our HomeController __contruct method. Now we want to call it using a name like "itechtuto". For this we have to register our middleware inside Kernel.php file.



    namespace App\Http;


    use Illuminate\Foundation\Http\Kernel as HttpKernel;


    class Kernel extends HttpKernel
    {

    protected $routeMiddleware = [

    'itechtuto' => \App\Http\Middleware\ItechxpertMiddleware::class,
    ];


    now itechtuto is our Middleware name. now we can use it like below.

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Http\Middleware\ItechxpertMiddleware;

    class HomeController extends Controller
    {
    // public function __construct()
    // {
    // $this->middleware(ItechxpertMiddleware::class);
    // }

    public function __construct()
    {
    $this->middleware('itechtuto'); //Now we can call it like that
    }

    }

    Route

    you can define the middleware directly to the routes .

    File name : index.php

    Route::get('/test', 'HomeController@test')->middleware('itechtuto');

    output :- Hello Itechxpert

    File name : index.php


    Login Application Using Middleware

    File name : CreateUsersTable

    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateUsersTable extends Migration
    {
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
    Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('email');
    $table->timestamp('email_verified_at')->nullable();
    $table->boolean('is_admin')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
    });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
    Schema::dropIfExists('users');
    }
    }

    File name : User.php

    <?php

    namespace App;

    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;

    class User extends Authenticatable
    {
    use Notifiable;

    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
    'name', 'email', 'password', 'is_admin'
    ];

    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $hidden = [
    'password', 'remember_token',
    ];

    /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */
    protected $casts = [
    'email_verified_at' => 'datetime',
    ];
    }

    File name :

    php artisan migrate

    File name :

    composer require laravel/ui

    File name :

    php artisan ui bootstrap --auth

    Create IsAdmin Middleware

    File name :

    php artisan make:middleware IsAdmin

    File name :

    <?php

    namespace App\Http\Middleware;

    use Closure;

    class IsAdmin
    {
    /**
    * Handle an incoming request.
    *
    * @param \Illuminate\Http\Request $request
    * @param \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
    if(auth()->user()->is_admin == 1){
    return $next($request);
    }

    return redirect(‘home’)->with(‘error’,"You don't have admin access.");
    }
    }

    kernel

    File name : Kernel.php

    protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'is_admin' => \App\Http\Middleware\IsAdmin::class,
    ];

    route

    File name : web.php

    Route::get('admin/home', 'HomeController@adminHome')->name('admin.home')->middleware('is_admin');

    Add Method on Controller

    File name : HomeController.php

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    class HomeController extends Controller
    {
    /**
    * Create a new controller instance.
    *
    * @return void
    */
    public function __construct()
    {
    $this->middleware('auth');
    }

    /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Contracts\Support\Renderable
    */
    public function index()
    {
    return view('home');
    }

    /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Contracts\Support\Renderable
    */
    public function adminHome()
    {
    return view('adminHome');
    }

    }

    Create Blade file

    File name : home.blade.php

    @extends('layouts.app')

    @section('content')
    <div class="container">
    <div class="row justify-content-center">
    <div class="col-md-8">
    <div class="card">
    <div class="card-header">Dashboard</div>
    <div class="card-body">
    You are normal user.
    </div>
    </div>
    </div>
    </div>
    </div>
    @endsection

    File name : adminHome.blade.php

    @extends('layouts.app')

    @section('content')
    <div class="container">
    <div class="row justify-content-center">
    <div class="col-md-8">
    <div class="card">
    <div class="card-header">Dashboard</div>
    <div class="card-body">
    You are Admin.
    </div>
    </div>
    </div>
    </div>
    </div>
    @endsection

    Update on LoginController

    File name : Http/Controllers/Auth/LoginController.php

    <?php

    namespace App\Http\Controllers\Auth;

    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Http\Request;

    class LoginController extends Controller
    {
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
    * Where to redirect users after login.
    *
    * @var string
    */
    protected $redirectTo = '/home';

    /**
    * Create a new controller instance.
    *
    * @return void
    */
    public function __construct()
    {
    $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {
    $input = $request->all();

    $this->validate($request, [
    'email' => 'required|email',
    'password' => 'required',
    ]);

    if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
    {
    if (auth()->user()->is_admin == 1) {
    return redirect()->route('admin.home');
    }else{
    return redirect()->route('home');
    }
    }else{
    return redirect()->route('login')
    ->with('error','Email-Address And Password Are Wrong.');
    }

    }
    }

    Create Seeder

    File name :

    php artisan make:seeder CreateUsersSeeder

    CreateUsersSeeder.php

    File name :

    <?php

    use Illuminate\Database\Seeder;
    use App\User;

    class CreateUsersSeeder extends Seeder
    {
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
    $user = [
    [
    'name'=>'Admin',
    'email'=>'admin@gmail.com',
    'is_admin'=>'1',
    'password'=> bcrypt('123456'),
    ],
    [
    'name'=>'User',
    'email'=>'user@gmail.com',
    'is_admin'=>'0',
    'password'=> bcrypt('123456'),
    ],
    ];

    foreach ($user as $key => $value) {
    User::create($value);
    }
    }
    }

    File name :

    php artisan db:seed --class=CreateUsersSeeder





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here


    Ittutorial