Search code examples
laravellaravel-routing

Is there another, more efficient way to nest prefix and name prefix in laravel 8 that doesn't need to use so many groups?


I saw a good way to nest prefix and name prefix, but this is so verbose. In addition, for few requests, it's acceptable, but when there is a lot of requests, creating groups can be problematic. This is a toy example.

Route::prefix('auth')->group(function () {
    Route::name('auth.')->group(function () {
        Route::get('login', [MainController::class, 'login'])->name('login');
        Route::get('register', [MainController::class, 'register'])->name('register');
    });
});

I try this, but it failed.

Route::name('auth.')->group(['prefix'=>'auth'], function () {
    Route::get('login', [MainController::class, 'login'])->name('login');
    Route::get('register', [MainController::class, 'register'])->name('register');
});

Is there another, more efficient way to nest prefix and name prefix in laravel 8 that doesn't need to use so many groups?

I'm using the Laravel 8 Documentation's route group section.


Solution

  • You can combine your prefixes, names and middlewares in the group function which will tidy things up somewhat:

    Route::group(['prefix' => 'auth', 'as' => 'auth.'], function () {
        Route::get('login', [MainController::class, 'login'])->name('login');
        Route::get('register', [MainController::class, 'register'])->name('register')
    });
    

    If you want to specify middleware on the group, just add it to the array in the first argument for the group function.

    Route::group(['prefix' => 'auth', 'as' => 'auth.', 'middleware' => [...]], function () {
        ...
    });