Search code examples
laravellaravel-5.3

Listing middleware in kernel.php


I have an admin middlware AdminMiddleware.php

 public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::check())
        {
            if($request->user()->is_admin==1)
            {
               return $next($request);
            }
             return redirect('/login');    
        }
        else
        {
          return redirect('/login');   
        }
    }

And i have some routes under adminmiddleware:

Route::group(['middleware' => ['App\Http\Middleware\Adminmiddleware']], function () {
        //admin routes
        });

Working properly. And i'm litte confused on Registering middleware? Why should i register. Only for alias or something more effective?


Solution

  • For $routeMiddleware and $middlewareGroups, they are mostly for aliasing. As you mentioned, you can don't register it and use it just fine in your route file.

    It's more on conveniency for your to swap the implementation shall you need to.

    IMO, register it so that you can swap the middleware implementation at any point of time without going into your route configuration file to change it - which is more error prone than one central location to change.