Sok Mengheang Sok Mengheang - 2 months ago 14
PHP Question

laravel 5.2 many to many relation retrieve data with intermediate table

I have tables :


products


  • id



categories


  • id



product_category


  • product_id

  • category_id




by using eloquent model relation, how to get all product data from a specific category id?

Answer

Assuming that you defined relationships on your models, you can try this:

$productName = 'Some product';

$category = Category::findOrFail($categoryId);
$product = $category->products->where('product_name', '=', $productName)->get();