I have just tried
$posts = Post::latest()->with('likes')->take(5)->get();
Using the demo project and Laravel Debug bar.
From 8 queries (with the N+1) problem you mention, I now have only 4 👍
See before and after
Hint: be sure to place the ->with('...') part BEFORE ->get() or ->all().
->with('...')
->get()
->all()
Actually, I was using the code in the index page and doing a @can ('like') and @can ('unlike') which was querying the DB twice per record. I changed the @can ('unlike') for @else and now the duplicate queries are gone. Thanks
Yes, that's because the gates in AuthServiceProvider are using User::hasLike :
public function hasLiked(Likeable $likeable): bool { if (! $likeable->exists) { return false; } return $likeable->likes() ->whereHas('user', fn($q) => $q->whereId($this->id)) ->exists(); }
You may change it to use a cache, like this (actual working solution) :
public function hasLiked(Likeable $likeable): bool { if (! $likeable->exists) { return false; } return $this->likes->contains( fn($like) => $like->likeable_type == get_class($likeable) && $like->likeable_id == $likeable->id ); }
It should minimize the number of queries. It's ugly but it works!
Result before with 15 queries (one per @can('like')) and after only 6!
@can('like')
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I have just tried
Using the demo project and Laravel Debug bar.
From 8 queries (with the N+1) problem you mention, I now have only 4 👍
See before and after
Hint: be sure to place the
->with('...')
part BEFORE->get()
or->all()
.Actually, I was using the code in the index page and doing a @can ('like') and @can ('unlike') which was querying the DB twice per record. I changed the @can ('unlike') for @else and now the duplicate queries are gone.
Thanks
Yes, that's because the gates in AuthServiceProvider are using User::hasLike :
You may change it to use a cache, like this (actual working solution) :
It should minimize the number of queries. It's ugly but it works!
Result before with 15 queries (one per
@can('like')
) and after only 6!