如何将一个路由添加到 2 个不同的中间件 (auth) 而不必在 Laravel 中复制它?

How can I add one route to 2 different middleware (auth) without having to duplicate it in Laravel?

我知道这是一个基本的 laravel 问题,但不知道该怎么做。如何将一个路由添加到 2 个不同的中间件 (auth) 而不必复制它?

// =admin
Route::group(['middleware' => ['auth']], function() {
    Route::get('/dashboard', 'App\Http\Controllers\DashboardController@index')->name('dashboard');
    Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});
// =cashier
Route::group(['middleware' => ['auth', 'role:cashier']], function() {
    Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController@showCashierProfile')->name('dashboard.cashier.profile');
    Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});

我有这条路线,我不想重复调用每个身份验证中间件:Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');

不能有两条路线相同 url。

Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');

这条路线在两个组内,由于 url 他们将产生相同的结果,因此只保留第二个。

Route::group(['middleware' => ['auth']], function() {
    Route::get('/dashboard', 'App\Http\Controllers\DashboardController@index')->name('dashboard');
    //Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
// this route will be ignored because the other one has the same url
});

Route::group(['middleware' => ['auth', 'role:cashier']], function() {
    Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController@showCashierProfile')->name('dashboard.cashier.profile');
    Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});

如果你想让Laravel对这两条路由进行不同的处理,你要加一个前缀:

Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => ['auth']], function() {
    Route::get('/dashboard', 'App\Http\Controllers\DashboardController@index')->name('dashboard');
    //Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
// this route will be ignored because the other one has the same url
});

Route::group(['prefix' => 'cashier', 'as' => 'cashier.',  'middleware' => ['auth', 'role:cashier']], function() {
    Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController@showCashierProfile')->name('dashboard.cashier.profile');
    Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});

这样,当 url 以 admin 为前缀时,第一个路由将被调用(没有 role:cashier 中间件)。

请注意,我添加了路由名称前缀 ('as' => 'admin.' / 'as' => 'cashier.'),因此您可以按名称调用每个路由,使用:

route('admin.make-a-sale.index'); // admin/make-a-sale
//or
route('cashier.make-a-sale.index'); // cashier/make-a-sale

补充一下,如果有人想修复下面的 Laravel blade 错误,每当您清除浏览器缓存并自动注销时:

*Attempt to read property "name" ...*

您需要将所有路线添加到:

Route::group(['middleware' => ['auth']], function () { 
    // routes here
});

一旦发生这种情况,这将重定向您以登录。