Laravel Eloquent Eager Loading where Condition Example

  584 views   6 months ago Laravel

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.

Author : Harsukh Makwana
Harsukh Makwana

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]