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