【问题标题】:Different middleware for resource route资源路由的不同中间件
【发布时间】:2021-04-27 13:57:53
【问题描述】:

我有一个资源控制器和一个路由:

Route::resource('/path', Controller::class)

对于这个控制器的每种方法,我需要使用不同的中间件。我可以在路由文件中而不是在 __construct() 方法中执行吗?

我需要这样的东西

Route::resource('/path', Controller::class)->middleware(['index' => 'guest', 'create' => 'auth'])

【问题讨论】:

  • 据我所知,使用单一的resource 路由定义方法是不可能的。也许你可以在laravel/ideas 中提出建议

标签: laravel


【解决方案1】:

您需要单独定义每个路由。

Route::resource('/path', Controller::class);

类似于:

Route::get('/path', [Controller::class, 'index'])->name('path.index');
Route::get('/path/create', [Controller::class, 'create'])->name('path.create');
Route::post('/path', [Controller::class, 'store'])->name('path.store');
Route::get('/path/{path}', [Controller::class, 'show'])->name('path.show');
Route::get('/path/{path}/edit', [Controller::class, 'edit'])->name('path.edit');
Route::put('/path/{path}', [Controller::class, 'update'])->name('path.update');
Route::delete('/path/{path}', [Controller::class, 'destroy'])->name('path.destroy');

使用第二个路由定义,您可以添加中间件。
所以:

Route::middleware('guest')->group(function () {
    Route::get('/path', [Controller::class, 'index'])->name('path.index');
    Route::get('/path/{path}', [Controller::class, 'show'])->name('path.show');
});
Route::middleware('auth')->group(function () {
    Route::get('/path/create', [Controller::class, 'create'])->name('path.create');
    Route::post('/path', [Controller::class, 'store'])->name('path.store');
    Route::get('/path/{path}/edit', [Controller::class, 'edit'])->name('path.edit');
    Route::put('/path/{path}', [Controller::class, 'update'])->name('path.update');
    Route::delete('/path/{path}', [Controller::class, 'destroy'])->name('path.destroy');
});

【讨论】:

    【解决方案2】:

    Controller Middleware

    class UserController extends Controller
    {
        /**
         * Instantiate a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth');
            $this->middleware('log')->only('index');
            $this->middleware('subscribed')->except('store');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2017-05-03
      • 1970-01-01
      • 2015-03-24
      • 2015-10-15
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多