$products = Product::whereHas('marks', function ($query) {
$query->where('products_marks.user_id', 2);
})->orderBy('created_at', 'desc')->paginate(10);
Docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have a products and a products_marks table. The products_marks table contains a user_id and a product_id and represents all products which are marked/saved by a user. So, this is more or less something like watch list.
My goal is now to perform a eloquent query which returns me only the products which are also present in the product_marks table for a certain user_id. For this example lets choose the user_id` 2.
This is my products.php model:
public function marks()
{
return $this->belongsToMany('App\Models\User', 'products_marks', 'product_id', 'user_id')->withTimestamps();
}
This is how I archive what I want at the moment. I perform a eloquent query with a join. But how can I do this with a relationship?
$products = Product::join('products_marks', 'products_marks.product_id', '=', 'products.id')
->where('products_marks.user_id', 2)
->orderBy('created_at', 'desc')
->paginate(10);
Kind regards and thank you!
$pageStatusIds = PageStatus::whereIn('status', [publish' , 'pending')->pluck('id')->toArray();
$products = Product::select('products.*')->join('products_marks', 'products_marks.product_id', '=', 'products.id')->whereHas('marks', function ($query) use ($user) {
$query->where('products_marks.user_id', $user->id);
})->whereIn('page_status_id', $pageStatusIds)->orderBy('products_marks.created_at', 'desc')->paginate(10);
But in that case you don't need whereHas
Please or to participate in this conversation.