skip to Main Content

I have the following api route:

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

In my api.php I have the following code for this:

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

In my v1/api/users.php I have this code:

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

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

My goal is to give the name a prefix users.. So that I can then the route name: users.delete or users.index as the name. Here my attempt: For this reason I tried to wrap the above code into a 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');

});

Problem However, Laravel then no longer recognises the wrapped routes. How can I rewrite this so that it works?

2

Answers


  1. Route name prefixes are configured as follows:

    Route::name('users.')->group(function () {
        Route::get('/users', function () {
            // Route assigned name "users.index"...
        })->name('index');
    });
    
    Login or Signup to reply.
  2. Base on your Routes you can chain the name() after the 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');
    });
    

    You can also use only the 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');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search