Route Model Binding: How to Change The Key

Laravel has a great feature of binding models by id field. So you can specify edit(User $user) and system would know to find the user from ID in the URL. But what if you want to bind by some other field?

Let's Remember how Route Model Binding Works

Example from the beginning. Let's say you have this URL: https://yourdomain.com/users/1

In your routes/web.php you refer to it as resource Controller:

Route::resource('users', 'UserController');

Then, in the Controller, it points to show() method, like this:

public function show(User $user)
{
     return view('users.show', compact('user'));
}

In this case, Laravel "knows" that $user object is needed to be found by users.id field. So under the hood it's doing this:

$user = User::findOrFail($id); // $id comes from URL

How to Customize ID field?

What if you want your URL like this?
https://yourdomain.com/users/taylor or https://yourdomain.com/users/povilas? I mean, so that parameter would be name of the user, not ID.

It's easy to change. The only thing you need to do is add this method to Eloquent model app/User.php:

/**
 * Get the route key for the model.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'name';
}

Of course, in this case you need to make sure that this name field is unique, and is compatible with URL structure (doesn't contain any invalid or unclear characters).

Perhaps, slug is the best way to accomplish that, I recommend a package for it: spatie/laravel-sluggable

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 57 courses (1055 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials