Question: Listing middleware in kernel.php

Question

Listing middleware in kernel.php

Answers 2
Added at 2017-01-01 13:01
Tags
Question

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?

Answers
nr: #1 dodano: 2017-01-01 13:01

Registering middleware is loading the class with each request automatically. You're telling Laravel to load and register it, so you could use it in routes and controllers without initializing it manually. Same with console commands, service providers etc. You must register before using them.

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

nr: #2 dodano: 2017-01-01 14:01

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.

Source Show
◀ Wstecz