Laravel Controller Middleware

Controller Middleware

Middleware can be assigned to the controller`s routes in our route files:

Route::get(‘profile’, ‘UserController@show’) ->middleware(‘auth’);

It is more convenient to specify middleware within our controller`s constructor. Using the middleware method from our controller`s constructor, we can easily assign middleware to the controller`s action.

We even restrict the middleware to only certain methods on the controller class:

class UserController extends Controller
 {
    /**
     * Instantiate a new controller instance.
     *
     * @return void 
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('log')->only('index');
        $this->middleware('subscribed')->except('store'); 
    }
} 

Controllers allow us to register middleware using a closure. It provides a convenient way to define a middleware for a single controller without defining an entire middleware class:

$this->middleware(function ($request, $next)
 {
 // ……….
 return $next($request);
 }); 

We assign middleware to a subset of controller actions; however, it indicates our controller is growing too large. Consider breaking our controller into multiple, smaller controllers.