Search code examples
phplaravelmiddleware

Is there any difference between assigning middleware in a route group and launching it in controler's constructor?


I am wondering if there is any adifference between asiigning middleware in a route like this :

Route::patch('/edit/{column}/{id}',['middleware' => 'auth', 'uses' => 'ResourceController@editCompany']); 

and launching it in controller's constructor

public function __construct()
{
  $this->middleware('auth');
}

Is it the same? Does it do anything else then checking if I am logged in?


Solution

  • It is completely the same. The problem is when you add that in the constructor you need to remember to add it in every new controller that you want to be auth protected.

    While in the routes file, you can group multiple endpoints and apply the middleware in all of them:

    Route::group(['middleware' => 'auth'], function() {
     // all routes here that need to be auth protected.
    });