Easy Implicit Route Model Binding Coming to Laravel 7

News

December 3rd, 2019

laravel-7-route-binding.png

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

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

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

1<?php
2 
3class Post extends Model
4{
5 /**
6 * Get the route key for the model.
7 *
8 * @return string
9 */
10 public function getRouteKeyName()
11 {
12 return 'slug';
13 }
14}

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:

1Route::get('/posts/{post:slug}', function (Post $post) {
2 // ...
3});
4 
5// Or you could use the default `{post}` here...
6Route::get('/admin/posts/{post:id}/edit', function (Post $post) {
7 // ...
8});

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

1laravel new example --dev

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.