UrlRoutable in Laravel 5
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
Laravel 5 includes a great new feature (biased as I may be) that I made the initial pull request for. It's the new Illuminate\Contracts\Routing\UrlRoutable
interface to be used with Eloquent models. It makes generating routes just a little bit simpler and keeps your code DRYer. Let's take a look at how it works.
Previously, if we wanted to route to a post we would need to do something like this.
If we decided we'd rather use a post's slug instead of it's ID to make the site prettier we would need to change every URL on the site to reflect this.
However, in Laravel 5 this is now handled by the model. The UrlRoutable
contract includes a method called getRouteKeyName()
which returns the model's key (usually 'id'). It means now you can simply pass the model to the route()
method to get the URL generated.
And now, if you want to use a slug instead of the primary key you can simply override that method in your model.