【问题标题】:How to assign middleware partially to Laravel resource routes?如何将中间件部分分配给 Laravel 资源路由?
【发布时间】:2021-08-17 05:08:12
【问题描述】:

如何将身份验证中间件分配给部分资源路由?

此代码是帖子的资源路径

Route::apiResource('posts', PostController::class);

可以解释如下

Route::get('posts', [PostController::class, 'index']);
Route::get('posts/create', [PostController::class, 'create']);
Route::get('posts/{id}', [PostController::class, 'show']);
Route::get('posts/{id}/edit', [PostController::class, 'edit']);
Route::post('posts', [PostController::class, 'store']);
Route::put('posts/{id}', [PostController::class, 'update']);
Route::delete('posts/{id}', [PostController::class, 'destroy']);

我只想将身份验证中间件分配给destroy 方法或storeupdate 等。

有什么方法可以让我坚持使用Route::apiResource('posts', PostController::class);,但为部分路由分配了身份验证中间件?

【问题讨论】:

  • 您可以在控制器的构造函数中分配中间件
  • 如果我使用控制器构造函数,所有方法都可以在授权后使用。

标签: laravel


【解决方案1】:

您需要使用正是它的目的的门,以允许或禁止某些操作 https://laravel.com/docs/8.x/authorization

就像你说的,如果你使用中间件,你将允许或禁止所有。

【讨论】:

    【解决方案2】:

    在你的控制器构造函数中

      public function __construct()
        {
            
            $this->middleware('auth', ['only' => ['destroy ']]);
        }
    

    这只会将 auth 中间件应用于 destory 方法。

    参考:https://laravel.com/docs/5.0/controllers#controller-middleware

    【讨论】:

      【解决方案3】:

      您可以通过在您的PostController__construct() 方法中调用middleware 方法来做到这一点

      仅使用 ... 方法绑定中间件:

      public function __construct()
      {
          $this->middleware('auth')
              ->only([
                  'destroy',
                  'store',
                  'update',
              ]);
      }
      

      或绑定到除 ... 之外的所有方法:

      public function __construct()
      {
          $this->middleware('auth')
              ->except([
                  'show',
                  'index',
              ]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 2019-11-23
        相关资源
        最近更新 更多