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

问题描述 投票:0回答:2

我知道这是一个基本的 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');

php laravel authentication routes middleware
2个回答
0
投票

不能有两条具有相同网址的路由。

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

0
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.