Laravel 中间件 Route::group 除外

Laravel Middleware except with Route::group

我正在尝试为管理部分创建一个组路由,并将中间件应用于除登录和注销之外的所有路径。

我目前拥有的是:

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'authAdmin'], function() {

    Route::resource('page', 'PageController');
    Route::resource('article', 'ArticleController');
    Route::resource('gallery', 'GalleryController');
    Route::resource('user', 'UserController');

    // ...

});

如何使用上述设置为中间件声明异常?

只需嵌套组,然后您就可以排除特定路由:

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {

    Route::get('login', 'AuthController@login');
    Route::get('logout', 'AuthController@logout');

    Route::group(['middleware' => 'authAdmin'], function(){
        Route::resource('page', 'PageController');
        Route::resource('article', 'ArticleController');
        Route::resource('gallery', 'GalleryController');
        Route::resource('user', 'UserController');

        // ...
    });
});

您还可以使用 laravel 的 withoutMiddleware 方法,如下所示;

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'authAdmin'], function() {

  Route::resource('page', 'PageController');
  Route::resource('article', 'ArticleController');
  Route::resource('gallery', 'GalleryController');
  Route::resource('user', 'UserController');

  Route::get('login', 'AuthController@login')->withoutMiddleware([AuthAdminMiddleware::class]);
  Route::get('logout', 'AuthController@logout')->withoutMiddleware([AuthAdminMiddleware::class]);
});