Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between middleware in routes and middleware in controller's constructor?

Tags:

php

laravel

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?

like image 596
Zain Farooq Avatar asked Nov 28 '25 23:11

Zain Farooq


1 Answers

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

like image 73
Prashant Deshmukh..... Avatar answered Nov 30 '25 13:11

Prashant Deshmukh.....



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!