Laravel -是否可以将一般路线名称作为路线组传递?

waxmsbnn  于 2022-12-01  发布在  其他
关注(0)|答案(2)|浏览(120)

我有下面的api路线:

GET /api/v1/users
POST /api/v1/users // middleware auth

在我的api.php中,我有以下代码:

Route::group(['prefix' => 'v1'], function() {
    require __DIR__ . '/v1/api/users.php';
});

在我的v1/api/users.php中,我有以下代码:

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/users', function (Request $request) {
        return [];
    })->name('create');
});

Route::get('/users', function (Request $request) {
    return [];
})->name('index');

我的目标是给名称一个前缀users. .这样我就可以接着路由名称:users.deleteusers.index作为名称。**以下是我的尝试:**因此,我尝试将上面的代码 Package 到Route::group:

Route::group(['name' => 'users.'], function() {

    Route::middleware('auth:sanctum')->group(function () {

        Route::post('/users', function (Request $request) {
            return $request->user();
        })->name('delete');

        Route::get('/users', function (Request $request) {
            return [];
        })->name('index');

});

问题然而,Laravel不再识别包裹的路线。我如何重写它才能工作?

gwo2fgha

gwo2fgha1#

路由名称前缀配置如下:

Route::name('users.')->group(function () {
    Route::get('/users', function () {
        // Route assigned name "users.index"...
    })->name('index');
});
dbf7pr2w

dbf7pr2w2#

根据您的路线,您可以将name()链接到middleware()之后:

Route::middleware('auth:sanctum')->name('users.')->group(function () {

    Route::post('/users', function (Request $request) {
        return $request->user();
    })->name('delete');

    Route::get('/users', function (Request $request) {
        return [];
    })->name('index');
});

您也可以只使用group()

Route::group(['name' => 'users.', 'middleware' => 'auth:sanctum'], function() {
    Route::post('/users', function (Request $request) {
        return $request->user();
    })->name('delete');

    Route::get('/users', function (Request $request) {
        return [];
    })->name('index');
});

相关问题