Laravel eloquent eager loading where condition example

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.

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment