Search code examples
phplaraveleloquenteloquent-relationship

How to display related products through pivot table?


I want to display related item which is in same category.

Here is my 3 table structure

food item table : "food_item_id",

"name" ,

"image" ,

food item category table :

"food_item_category_id"

"name"

pivot table

id,

food_item_id

food_item_category_id

FooItem model:

public function foodItemCategory() {
    return $this->belongsToMany(FoodItemCategory::class, 'food_items_have_categories', 'food_item_id', 'food_item_category_id')
        ->withPivot('food_item_id', 'food_item_category_id')
        ->withTimestamps();
}

Food Category Model:

 public function foodItem() {
    return $this->belongsToMany(FoodItem::class, 'food_items_have_categories', 'food_item_category_id', 'food_item_id')
        ->withPivot('food_item_id', 'food_item_category_id')
        ->withTimestamps();
}

I want to get all food items from a specific category. Suppose a user clicks on a food item which Id is 1 and It is belongs to category ID 2. Now I want to show more food items which is in the category ID 2. I want to display that in my view blade. Now, how can I display the related products in view which is in the same category?


Solution

  • As your relation is many to many, you can do this:

    $food = FoodItem::find(1);
    $categories = $food->foodItemCategory;
    $items = [];
    foreach($categories as $category) {
       $items[$category->id] = $category->foodItem;
    }
    

    then you can pass $items to your blade template.