Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.* multiple middleware whole controller

Tags:

php

laravel-5

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?

like image 594
WebArtisan Avatar asked Feb 03 '16 22:02

WebArtisan


1 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.

like image 122
Grzegorz Gajda Avatar answered Oct 03 '22 14:10

Grzegorz Gajda