I am quite new to the laravel and want to understand about middlewares in deep. I want to know that what is the major difference between attaching middleware with the route or adding the middleware in the controller's constructor.
For example it is a constructor of the controller named UserController
public function __construct() {
$this->middleware('age');
}
Let's assume that it is the route of the same controller i.e UserController
Route::get('user/profile', function () {
//
})->middleware('age');
My main question is that should I need to add middleware in both routes and controller's constructor or just in one of them?
Both will perform same task,it`s just you can write in two different ways.
However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action. You may even restrict the middleware to only certain methods on the controller class.
https://laracasts.com/discuss/channels/laravel/middleware-in-controller-or-on-route
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With