ItSolutionStuff.com

Laravel Eloquent Always Load Model Relation Example

By Hardik Savani • November 5, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

Laravel Eloquent without() and withOnly() Method Example

Read Now →

Laravel Replicate Model with Relationships Example

Read Now →

Laravel Order By Relation Column Example

Read Now →

Laravel Relationship Eager Loading with Condition Example

Read Now →

Laravel Relationship Eager Loading with Count Example

Read Now →

Laravel Relationship Eager Loading Example

Read Now →

Laravel Relationship Where Condition Example

Read Now →

Laravel Eloquent Relationships Tutorial From Scratch

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Polymorphic Relationship Tutorial

Read Now →

Laravel Many to Many Polymorphic Relationship Tutorial

Read Now →