How are all the relations ?
Nov 25, 2015
4
Level 10
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?
Level 52
Something like that :
Post::with('user')->with(['favorites' => function($query) {
$query->where('favorites.user_id', auth()->id);
}])->get();
4 likes
Please or to participate in this conversation.