Posts Learn Components Snippets Categories Tags Tools About
/

Route Model Binding With Relationship in Laravel 8

Learn how to load relationship in laravel from model binding instance in Laravel 8

Created on Jun 26, 2021

1358 views

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);
}

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

)