Home » Php » php – Laravel 5.* multiple middleware whole controller

php – Laravel 5.* multiple middleware whole controller

Posted by: admin July 12, 2020 Leave a comment

Questions:

How can i define multiple middlewares for all routes in particular controller?
Yes, i can define one midd in __constructor like:

$this->middleware( 'somemidd' );

and yes, i can define multiple midds for route like:

Route::get('/', ['middleware' => ['MyMiddleware', 'MySecondMiddleware'], function () {
    //
}]); 

define multiple midds for Route::resourse is not solution, coz i have custom methods in my controller.
And i dont want to put midd in global scope Kernel\ protected $middleware = …

How can i solve this?

How to&Answers:

You can use Middleware Groups:

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

Also you can use many middlewares in __construct() method:

class UserController extends Controller
{
    /**
     * Instantiate a new UserController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log', ['only' => [
            'fooAction',
            'barAction',
        ]]);

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

More: HTTP Controllers, HTTP Middleware.