Jaroslaw Nowak
Jaroslaw Nowak

Reputation: 115

How to get data from additional table in many to many relationship?

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

Answers (2)

Prashant Deshmukh.....
Prashant Deshmukh.....

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

lagbox
lagbox

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

Related Questions