Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JillzTom's avatar

Eager loading with condition

I've a post table, a user table and a favorites table. There can be many favorites for a post. Now when I eager load the post with favorites, I want to check if the current logged in user has already favorited the particular post.

Post::with('user')->with('favorites')->get();

I can get the count of favorites using count($post->favorites).

But how do I check if the Auth::id() is equal to the $post->favorites[3]->user_id since the favorites is an array of user objects :/

How can I do this?

0 likes
4 replies
JillzTom's avatar

@bestmomo : User has many posts, post belongs to a user, post has many favorites and one favorite belongs to a posts, and a user.

//Post.php
public function favorites()
    {
        return $this->hasMany('App\Favorite', 'post_id', 'id');
    }
//Favorite.php
public function user()
    {
        return $this->belongsTo('App\User');
    }

public function post()
    {
        return $this->belongsTo('App\Post');
    }
bestmomo's avatar
Level 52

Something like that :

Post::with('user')->with(['favorites' => function($query) {
    $query->where('favorites.user_id', auth()->id);
}])->get();
4 likes
phamduchuy552's avatar

@bestmomo This is a bit old but if the user is not logged in, with() is still triggered and there is still an additional query for fetching 'favorites'. Is there any other way to avoid this, beside using if condition with auth()->id? Or it is the only way

Please or to participate in this conversation.