News

Easy Implicit Route Model Binding Coming to Laravel 7

Published
Easy Implicit Route Model Binding Coming to Laravel 7 image

In the next major release of Laravel coming in February 2020, you can customize implicit route model bindings directly in the route definition:

Route::get('/posts/{post:slug}', function (Post $post) {
// ...
});

Currently, Laravel 6 and below requires you to define a getRouteKeyName() method on the model like so:

<?php
 
class Post extends Model
{
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
}

You will still be able to use the getRouteKeyName() method; however, I feel like customizing it directly in the route definition makes it more flexible.

Perhaps you have multiple routes that you want to bind differently. For example, the frontend route uses slugs to display posts and backend admin uses ids to manage posts:

Route::get('/posts/{post:slug}', function (Post $post) {
// ...
});
 
// Or you could use the default `{post}` here...
Route::get('/admin/posts/{post:id}/edit', function (Post $post) {
// ...
});

If you want to start experimenting with customizing implicit route model binding, you can install the development version of Laravel:

laravel new example --dev
Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article