Laravel 中间件(除了路由::组)

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

到目前为止,我所拥有的是:

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');

    // ...

});

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


答案 1

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

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');

        // ...
    });
});

答案 2

您也可以使用laravel的无中间件方法,如下所示;

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]);
});

推荐