How to remove id from url in laravel?

by haylee.mertz , in category: Third Party Scripts , 10 days ago

How to remove id from url in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 9 days ago

@haylee.mertz 

To remove the ID from the URL in Laravel, you can use route model binding. Route model binding allows you to automatically inject model instances directly into your routes.


Here's how you can do it:

  1. Define a route with parameter without the ID:
1
Route::get('user/{user}', 'UserController@show');


  1. Create a controller method that accepts the User model:
1
2
3
public function show(User $user) {
    return view('user.show', compact('user'));
}


Now, when you visit the URL /user/1, Laravel will automatically fetch the user with ID 1 from the database and pass it to the show method in your controller. You can then use this user object in your view without having to explicitly pass the user ID.