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]
Repair grub after Installing Windows on Preinstalled Ubuntu
You might want to use Windows and Ubuntu...Laravel 8 Vue JS CRUD Operation Single Page Application
Throughout this Laravel Vue js CRUD exam...How to Run Android Apps on Linux
Android is the most popular Smartphone o...How to compare two strings in PHP
Use the PHP strcmp() function...Laravel Eloquent One to Many Polymorphic Relationship Tutorial with Example
In a database structure, There are many...