Home > Software engineering >  How to implicitly binding multiple Eloquent models in a single route definition?
How to implicitly binding multiple Eloquent models in a single route definition?

Time:05-21

Laravel9 document says:

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 previous Eloquent model. For example, consider this route definition that retrieves a blog post by slug for a specific user:

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

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the User model has a relationship named posts (the plural form of the route parameter name) which can be used to retrieve the Post model. Blockquote

but it returns error :BadMethodCallException Call to undefined method App\Models\User::posts()

CodePudding user response:

Let me highlight this sentence the second Eloquent model such that it must be a child of the previous Eloquent model

based on the highlighted sentence, you must define a posts relationship function in the User model because Laravel supposes that the second segment is the child of the first segment which means that the first segment must have a hasMany relationship with the second segment like so,

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