Reputation: 115
I have a many to many relationship between tables 'products' and 'recipes'. I created table product_recipe to handle this and my table looks like:
id | recipe_id | product_id | amount
In my blade file I use
@foreach($recipe->product as $row)
<p>{{ $row->name }}</p>
@endforeach
to get a name of used products in recipe. How I can get an amount of product which is stored in product_recipe table? Do I have to create a model for product_recipe table and get it from model?
Upvotes: 0
Views: 273
Reputation: 2292
You have to use pivot
attribute.
@foreach($recipe->product as $row)
<p>{{ $row->pivot->field_name}}</p>
@endforeach
No need to create Model for product_recipe
. Just specify table name in relation of two Models.
Like return $this->belongsToMany('App\Product', 'product_recipe')->withPivot('amount');
and similar for other model.
Upvotes: 2
Reputation: 50541
You will have to declare the relationship wants to include the extra pivot information so that the pivot object that is attached to the records will have more than just the 'id's:
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('amount');
}
Now the pivot
object will include the field amount
:
foreach ($recipe->products as $product) {
echo $product->pivot->amount;
}
"By default, only the model keys will be present on the
pivot
object. If your pivot table contains extra attributes, you must specify them when defining the relationship"
Laravel 6.x Docs - Eloquent Relationships - Many To Many - Retrieving Intermediate Table Columns withPivot
Upvotes: 2