Posts Learn Snippets Categories Tags 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

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

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.