Laravel Eloquent Always Load Model Relation Example

By Hardik Savani November 5, 2023 Category : Laravel

Hi Folks,

This tutorial will give you an example of laravel model load relationship. you will learn laravel model always load relation. you will learn laravel model load default relation example. you can see laravel model automatic eager load relation example. follow the below step for laravel model $with relationship.

Sometime, we define relationship and we need eager load relation that we can do it using with(). But we always require to get that eager load relation then how to can we do it, like when we get post i always require comments so something like that how can possible. Laravel eloquent model provide $with variable where you can define default and always load relationship there. You can see the following one way to do this.

Create Post Model with $with variable

Here, we will create Post model and define a $with property, and declare the name of model that you always want to eager load. so, let's see the model code:

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

use HasFactory;

protected $with = ['comments'];

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'title', 'body', 'slug'

];

/**

* Get the comments for the blog post.

*/

public function comments()

{

return $this->hasMany(Comment::class);

}

}

Get Post with comments

Now, you will always get post with comments like following way:

$post = Post::find($id);

$post->comments;

I hope it can help you...

Tags :
Shares