Route Model Binding Improvements in Laravel 7

Hey Artisan

I think you have already known that route model binding is enhanced by taylor otwell in Laravel 7. Today i will show you how route model binding works in Laravel 7. Using route model binding we can specify our url parameter. 

Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. Sometimes you may wish to resolve Eloquent models using a column other than id. To do so, Laravel 7 allows you to specify the column in the route parameter definition.

route-model-binding-laravel-7

To do it we need to speciy the key name in our model like below

public function getRouteKeyName()
{
    return 'slug';
}

 

But in Laravel 7, no need to do that. We can return key name without calling above method inside model. So let's check it.

Route::get('api/posts/{post:slug}', function (App\Post $post) {
    return $post;
});

Now its works like laravel 6. Hope you understand. Here {post:slug} post model name and slug key name which you are going to return.

Automatic Scoping in Route Model Binding

Sometimes, when implicitly binding multiple Eloquent models in a single route definition, you may wish to scope the second Eloquent model such that it must be a child of the first Eloquent model. For example, consider this situation that retrieves a blog post by slug for a specific user:

In this situation what will you do ?  see the below example

use App\Post;
use App\User;

Route::get('api/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
})

 

Look, In this case, it will be assumed that the User model has a relationship named posts (the plural of the route parameter name) which can be used to retrieve the Post model. Hope you got the point.

Now just you have to make a posts methos inside User model.

App\User.php

public function posts() {
  
   return $this->hasMany(Post::class);

}

Read also : Laravel 6 REST API with JWT Authentication

Now if you run this above code you will see the single post of the specific user. You must be define this relationship otherwise it won't work in laravel 7. Hope it will help you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website