Saman
Saman

Reputation: 601

Get column value from Many to Many Relationship in Laravel

This is my tables structure: enter image description here

Attribute.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
   protected $guarded = [];

   public function products()
   {
       return $this->belongsToMany('App\Product');
   }

}

Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
   protected $guarded = [];

   public function attributes()
   {
       return $this->belongsToMany('App\Attribute');
   }

}

I want to get the value column for each row.
What code should I write in my controller to access this value?
Laravel version: 6.9.0
Thanks

Upvotes: 1

Views: 2798

Answers (2)

Md. Amirozzaman
Md. Amirozzaman

Reputation: 1125

When we implements Many To Many relationship,it default create a intermediate table

In your case that table is attribute_product table, we might reference this table as Pivot table.

This tables value was retrieve by those model by pivot attribute name as follows:

$product = App\Product::find(1);

foreach ($product->attributes as $attribute) {
    echo $attribute->pivot->product_id;
}

To add Extra column in (Pivot table)

By default, only the model keys [$attribute_id,$product_id] will be present on the attribute_product table. If your pivot table contains extra attributes, you must specify them when defining the relationship:

return $this->belongsToMany('App\Attribute')->withPivot('column1', 'column2','value');

To change pivot Attribute Name to your given name

you may wish to rename your intermediate table accessor to values instead of pivot.

return $this->belongsToMany('App\Attribute')
                ->as('values')

Then you will retrieve by $attribute->values->product_id instead of $attribute->pivot->product_id

Upvotes: 1

Mehedi Hasan
Mehedi Hasan

Reputation: 154

You can solve this problem by adding the following method of your end of the relationship

withPivot(['value']);
public function attributes()
{
    return $this->belongsToMany('App\Attribute')->withPivot(['value']);
}

And also

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot(['value']);
}

Upvotes: 2

Related Questions