如何为特定控制器中的所有路由定义多个中间件? 是的,我可以在__constructor中定义一个midd,如:
$this->middleware( 'somemidd' );
是的,我可以为路线定义多个midd:
Route::get('/', ['middleware' => ['MyMiddleware', 'MySecondMiddleware'], function () {
//
}]);
为Route :: resourse定义多个midds不是解决方案,因为我在我的控制器中有自定义方法。 而且我不想把midd放在全局范围内Kernel \ protected $ middleware = ...
我该如何解决这个问题?
答案 0 :(得分:10)
您可以使用中间件组:
/**
* 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',
],
];
此外,您可以在__construct()
方法中使用许多中间件:
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',
]]);
}
}