DEV Community

Discussion on: How to implement a simple like system with Laravel

 
bdelespierre profile image
Benjamin Delespierre • Edited

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();
    }
Enter fullscreen mode Exit fullscreen mode

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
        );
    }
Enter fullscreen mode Exit fullscreen mode

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!