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

AR's avatar
Level 7

Optimizing eloquent query

I have a page that checks whether if a product is liked by the logged in user and also the likes count.

I have read that if I write $this->likes->count() the process is slow the app first will create a collection with all the likes then it will count them. but I need two things. If I change the likes to likes() in my queries, it will do two requests to the db while if I have it as is (likes), it will only make one request. which way is more optimized in my case?

Here is my two methods for likescount and also isLiked:

protected $appends = [
    'isliked',
    'likescount',
];

public function isLiked()
{
    return !!$this->likes->where('user_id', auth()->id())->count();
}

public function getIsLikedAttribute()
{
    return $this->isLiked();
}

public function getLikesCountAttribute()
{
    return $this->likes->count();
}

and in my blade I call them like this:

{{ $product->isLiked }}
{{ $product->likescount }}

The only query regarding the likes table that gets running is :

select * from `likes` where `likes`.`liked_id` = '17' and `likes`.`liked_id` is not null and `likes`.`liked_type` = 'App\Product'

but when I change the likes to likes() in my isLiked() and getLikesCountAttribute() methods, I get these two queries:

select count(*) as aggregate from `likes` where `likes`.`liked_id` = '17' and `likes`.`liked_id` is not null and `likes`.`liked_type` = 'App\Product' and `user_id` = '1'

select count(*) as aggregate from `likes` where `likes`.`liked_id` = '17' and `likes`.`liked_id` is not null and `likes`.`liked_type` = 'App\Product'

Please advice

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well that because likes will return the fetch relationship as a collection and it will be cached on the model as well. However likes() will return the query builder and therefore it makes two database requests.

So it completely depends on your needs, but both methods are fine. It's just important to know the difference!

Please or to participate in this conversation.