James Parsons
James Parsons

Reputation: 925

How to add two middlewares in controller constructor

What would be the correct way to add these two middleware in the Controller constructor.

Route::get('admin', ['middleware' => ['auth', 'admin'], function()

I have the following which is clearly incorrect.

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

Upvotes: 5

Views: 13660

Answers (1)

devnull
devnull

Reputation: 1928

You can break it down to two statements as below

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

Or if you want to use one statement

public function __construct()
{
      $this->middleware(['auth', 'admin']);
}

However if you restrict the middleware for certain methods like below

 $this->middleware(['auth', 'admin'], ['except' => [
            'fooAction',
            'barAction',
        ]]);

In that case, you restrict both auth and admin for fooAction method and barAction method

Source:

https://laravel.com/docs/master/controllers#controller-middleware

Upvotes: 19

Related Questions