Ad

Get Column Value From Many To Many Relationship In Laravel

- 1 answer

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

Ad

Answer

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

Ad
source: stackoverflow.com
Ad