When getting eloquent queries as properties, the related models are always "lazy loaded". It means that the relationship data is not actually loaded until you first access the property. But, eloquent can be "eager load" relationships at the time you query the parent model.
That will prevent application to request on every property when current data is accessed. In the below example I have eager loaded the property query using with() method.
$posts = Post::with([
'comments as untouched_comments' => function (Builder $query) {
$query->where('replied', 1);
}
])->get();
The below example shows how to use advance query with where() condition.
$posts = Post::with([
'comments.user' => function (Builder $query) {
$query->where('replied', 1);
}
])->get();
If you want some query to load relationship data as eager loading, you may define a $with property on the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['author'];
/**
* Get the author that wrote the book.
*/
public function author()
{
return $this->belongsTo(Author::class);
}
}
I hope it will help you. Thanks for giving time in reading article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to Get Current Month Records in Laravel
You may want to add filter while fetchin...Laravel Eloquent One to One Relationship Tutorial with Example
While designing database structure, you...Laravel8 - Validation Required if Another Field is Empty
In this article, I will share with you h...Tilt.js Tiny Parallax tilt effect for jQuery
Tilt.js is a tiny requestAnimationFrame...How to convert URL to array in PHP
An URL is the string of many data. URL c...