Home / Snippets / Route Model Binding With Relationship in Laravel 8
Route Model Binding With Relationship in Laravel 8 cover

Route Model Binding With Relationship in Laravel 8

1.4K

3 years ago

0 comments

Laravel allows you to inject modal instance directly into the application route for easy retrieval and auto binding. But sometimes you might require their relationship to be included as well. To achieve this you can make use of the "with" property of the model class or by manually calling the relation through the "load" method.

For example, if you want to include the "comments" relationship to the "post" method, you can define it like below.

# app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $with = ['commenets'];


Otherwise, you can manually include the relation using the "load" method like below.
# app/Http/Controllers/PostController.php

public function show(Post $post)
{
    $postWithComments = $post->load('comments');

    dd($postWithComments);
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this