Many site has to deal with loads of different HTTP request on daily basis. Laravel Middleware filters the HTTP request from entering into your application. It is a type of the filtering mechanism. It verifies whether the user of the application is authenticated or not. If the user not authenticated then they will be redirected to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Middleware works in between request and response of your application.  It acts like a firewall between the request and response. It also examines the request and either proceed further or return back depending on the response. Laravel comes with several inbuilt middlewares like EncryptCookies, RedirectIfAuthenticated, TrustProxies etc. You can also create your own custom middleware. All middlewares are located in the app/Http/Middleware directory of Laravel app.

Creating Middleware

We can easily create a middleware using the artisan command.

php artisan make:middleware AdminMiddleware

Now let’s go to the folder app/Http/Middleware/AdminMiddleware.php and open it. There you will see a handle function with which you have to deal with.

Currently you handle function will look like this.

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

After we have created the middleware component, we need to look at modifying the code that suits our need.

Updating Middleware

Now we need to write the logic for filtering the request. If it satisfies the condition then it will proceed further. Otherwise, it will redirect back to the login screen or any other redirection screen you have define.

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

Registering Middleware

To make this middleware work you have to register it. For registering the middleware you will have two choices. First choices is that you have to add the middleware to run on every request handle by your app. You can do that by opening up App\Http\Kernel.php and adding it to your middleware array like so

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class, 
    // our new class.
    \App\http\Middleware\AdminMiddleware::class,
];

Second choice is to have the middleware run on registered routes only, you can register it like so:

<?php
/**
  * The application's route middleware.
  *
  * @var array
  */
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,    
     'admin' => \App\Http\Middleware\AdminMiddleware::class,
];

And then add the middleware to the specific routes like so:

Route::get('/admin', ['middleware' => 'admin', function() {
    return "ADMIN";
}]);

Conclusion

On this lesson, we discuss about basic of laravel middleware. You can add more complex logic and validations as per your requirements. If you wish to add to the discussion or would like to ask a question, then leave a comment below.

Comments

  1. Sweet blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it

Leave a Reply

Your email address will not be published. Required fields are marked *