Hi,
Love the code. Straight forward and works like a charm.
Is there a way to eager load the likes data on index pages?
I tried adding "likes" to the with query but it doesn't seem to reduce the amount of queries being performed.
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
Hi,
Love the code. Straight forward and works like a charm.
Is there a way to eager load the likes data on index pages?
I tried adding "likes" to the with query but it doesn't seem to reduce the amount of queries being performed.
Thanks
Can you show us what you tried?
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!