Home > Enterprise >  Add username as prefix in route URI in Laravel 9
Add username as prefix in route URI in Laravel 9

Time:12-19

I am building an application where users are registered and want to be redirected to their individual dashboard.

Now, its happening like

localhost/project/user/dashboard (here all users are accessing same URL)

but I want to make it like :

http://localhost/project/{username1}/dashboard, http://localhost/project/{username2}/dashboard

Googled lot but none of them are explained well and working.

Please assist with complete flow.

I have made this, and its working as

localhost/project/vendors/dashboard

Route::prefix('vendors')->group(function () { Route::middleware(['auth:vendor'])->group(function () { Route::get('/dashboard', [VendorController::class, 'dashboard'])->name('vendor.dashboard'); });
});

CodePudding user response:

You can specify route parameters in brackets like so {parameter}, change your code into this.

Route::get('project/{username}/dashboard', [UserDashboardController::class, 'dashboard'])
    ->name('user.dashboard');

In your controller you could access it like this.

class UserDashboardController
{
    public function dashboard(string $username)
    {
        User::where('username', $username)->firstOrFail();

        // something else
    }
}

Seems like in your routes your are mixing vendor prefix logic in with something that in your specifications of what your urls should look like does not match. Which i think is making up some of the confusion on this case.

CodePudding user response:

You can use route prefix like this

Route::prefix('{username}')->group(function () {
    Route::middleware(['auth'])->group(function () {
        Route::get('/dashboard', [UserController::class, 'dashboard'])->name('user.dashboard');
    });
});
  • Related