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

t0berius's avatar

favorite / liked items

Using a table to store all the "favourite" products of a user. User model:

public function favouriteProducts()
{
    return $this->belongsToMany('App\Product', 'favourite_products');
}

Now when I list the products, what's the best way, to decide either a user favors the product or not?

Product model:

public function favouriteUsers()
{
    return $this->belongsToMany('App\User', 'favourite_products');
}

I would like to prevent the database to be fired with a single query for every product I listed, just to check if the user favors the product or not.

For sure I could load the favouriteUsers (eager loaded) with the products and check the collection...any other idea than this?

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

products can eager load favourites but using a constraint on the eager load so that it only gets the favourites of the current user.

https://laravel.com/docs/5.7/eloquent-relationships#constraining-eager-loads

$products = Product::with(['favouriteUsers' => function($query){
        $query->where('user_id',Auth::id());
    }])->get();

and then only products with a favourite will be favourited by this user

1 like
t0berius's avatar

@snapey

Inside my listing I would need to display all products (paginated for sure). Beside every product is a button to "favor" the product or unfavor (in case user has already liked the product), think you understand what I mean now?

Snapey's avatar

Yes, and...

Does not alter my reply.


@if($product->favouriteUsers->count()) 
    <i class="fas fa-heart"></i>
@else
    <i class="far fa-heart"></i>
@endif

(using Font-awesome filled and outlined heart)

You can put your like / dislike links inside the same if/else

edit just changed the check after using this myself on a project

Please or to participate in this conversation.