Controller Middleware
Middleware can be assigned to the controllers routes in our route
files:
1 2 3 |
Route::get(‘profile’, ‘UserController@show’) ->middleware(‘auth’); |
It is more convenient to specify middleware within our
controllers constructor. Using the middleware method from our controllers constructor, we can easily
assign middleware to the controller
s action.
We even restrict the middleware to only certain methods on the controller class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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:
1 2 3 4 5 6 7 |
$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.