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

eddy1992's avatar

How to get data though relationship many to many ?

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.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

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.