As you must already know that at times if you don't eager load your relationship models it can lead of N+1 query problem, This happens when you are trying to get property from a relationship model inside a Loop.
Laravel Eloquent provides with method to eager load your relationship when you are querying the object model.
Eager Load on Demand
For this example we will consider two models.
1. Posts
2. Comments
A post can have many comments. Thus they Post will have hasMany relationship with Comments
public function comments(){
return $this->hasMany('App\Comments');
}
Thus, if you want to eager load the comments relationship along with Post, While querying the Post data you can do something like this
$posts = Post::with('comments')->latest()->get();
Always Eager Load
What if you decide in your application you always want to load comments along with Posts. This can be approaced in two ways.
1. Using $with property on Post Model
In your post Model, define a $with property, and declare the name of model that you always want to eager load.
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Reply extends Model
{
use RecordsActivity;
protected $guarded = [];
protected $with = ['comments'];
}
Once this magic property is defined, comments associated with your post will always be loaded in your Post query.
Downside of this approach is that, you cannot turn this off for certain instances. Your post query will always load the comments data.
2. Using Global Scope
Second way of always eager loading the relationships is via Global Scopes,
Here is how you can define a global scope to always load the comments data along with Post
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
class Post extends Model
{
protected $guarded = [];
protected static function boot(){
parent::boot();
static::addGlobalScope('comments', function($builder){
$builder->with('comments');
});
}
}
With this approach you can turn off the loading of comments data when you don't want it by using withoutGlobalScope method
Post::withoutGlobalScope()->latest()->get();
That's all about Eager Loading Relationship in Laravel.