Home > Software engineering >  Laravel routes prefix for protected and unprotected routes
Laravel routes prefix for protected and unprotected routes

Time:11-16

I have two types of routes.

  1. For guests and authenticated users
  2. For authenticated users only

For authenticated users only, i am using a middleware and i need to have a route prefix. My code look like this

Route::prefix('guests')->group(function () {
Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');
});

Route::middleware(['auth', 'role:user,admin'])->group(function () {
Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');
});

How can i have a route prefix if i already have a middleware in

Route::middleware(['auth', 'role:user,admin'])->group(function () {
Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');
});

CodePudding user response:

You can play with the Route methods and organize them how you want since they normally will return themselves.

In this case, as @Gert B. commented, you could do something like this:

Route::prefix('guests')->get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');

Route::prefix('admin')->middleware(['auth', 'role:user,admin'])->group(function () {
    Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');
});

But you could also do it this way too:

Route::prefix('guests')->group(function () {
    Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');

    // more guest routes here
});

Route::prefix('admin')->middleware(['auth', 'role:user,admin'])->group(function () {
    Route::get('/user_landing', [EngineController::class, 'user_landing'])->name('user_landing');

    // more admin routes here
});

Which will allow to add more routes.

But yeah, there is more ways to achieve the same. Just try to use the clearer ones, so you and others can understand it better.

  • Related