If you have worked with laravel for some time, you have worked with laravel route model binding. it is when you pass {user}
in the route, and the user object is available in your controller, magic haan...
But what if you need that for an entire group of routes? For the situation like below.
Route::prefix('/@{username}')->group(function () {
Route::get('/', [UserController::class, 'show'])->name('profile.show');
Route::get('questions/{question}', [QuestionController::class, 'show'])->name('questions.show');
});
And before you wonder, yes, this is a code snippet from pinkary. In the case above, we want the user in our controller based on the username passed in the URL.
To achieve this, we have to bind the {username}
with the User model. In your AppServiceProvider
, add the following line in the boot
method.
public function boot(): void
{
Route::bind('username', fn (string $username): User => User::where(DB::raw('LOWER(username)'), mb_strtolower($username))->firstOrFail());
}
Assumptions are there is a column in the users
table with the name username
Your controller should look something like this.
// UserController::class, 'show'
public function show(User $user): View
{
...
// QuestionController::class, 'show'
public function show(User $user, Question $question): View
{
...
Read more about it in the official documentation