Level 104
You're pretty much there...
$category = Category::findOrFail($id);
$category->products; // returns a Collection which you can iterate over
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi I have three tables one is categories table, products table, category_product table
in category_products tabl we save product_id and category_id in them
in Product Model I have defined a relation
public function categories()
{
return $this->belongsToMany('App\Category','category_product')->withTimeStamps();
}
In Category model I have dfined an inverse relationship
public function products()
{
return $this->belongsToMany('App\Product');
}
now how would I fetch the products on the basis of category id.
You're pretty much there...
$category = Category::findOrFail($id);
$category->products; // returns a Collection which you can iterate over
Please or to participate in this conversation.