Laravel Eloquent Always Load Model Relation Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Select Specific Columns in Laravel Eloquent Model?
- Laravel Eloquent without() and withOnly() Method Example
- Laravel Replicate Model with Relationships Example
- Laravel Order By Relation Column Example
- Laravel Relationship Eager Loading with Condition Example
- Laravel Relationship Eager Loading with Count Example
- Laravel Relationship Eager Loading Example
- Laravel Relationship Where Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to One Eloquent Relationship Tutorial
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel Has Many Through Eloquent Relationship Tutorial
- Laravel One to Many Polymorphic Relationship Tutorial
- Laravel Many to Many Polymorphic Relationship Tutorial