Home > OS >  Laravel Blade looping through products based on relationship values
Laravel Blade looping through products based on relationship values

Time:08-19

I am using Multiple Table Inheritance to assign attributes to different product types

products table | product_id | category | | -------- | -------------- | | xxx-1 | food | | xxx-2 | food | | xxx-3 | drink |

products_food table for food specific attributes | product_id | nutrition_group | | -------- | -------------- | | xxx-1 | fruit | | xxx-2 | snack |

With a product relationship

public function products_food() {
    return $this->hasOne('ProductFood::class','product_id')
}

If I have all products being sent to my blade template with the variable $products, how do I loop through every $product with a nutritional_group value of fruit?

I tried @foreach ($products->products_nutrition->where('nutritional_group','fruit') as $product) but that didn't work.

CodePudding user response:

You should be able to filter the collection with dot notation.

$products->where('products_food.nutritional_group', 'fruit') as $product
  • Related