Q:

Laravel many to many relationship, add more objects into "pivot"?

Usually a many to many relationship will return something like this:
Product::with('brands')->find(4);
{
  id: 4
  name: 
  price:
  brands: [
    id: 6
    pivot: {
      product_id: 4,
      brand_id: 6,
      // withPivot fields goes here if specified.
      // I want to add extra fields here too, unrelated to the database. e.g. :
      foo: 'bar'
    }

  ],
  suppliers: [

  ]
}

This is done in Product.php:
public function brands()
{
  return $this->belongsToMany('Brand');
}

Do we have any control over what goes into the pivot object? I understand it spits out the two foreign key ids and whatever withPivot you've included but I want to add another property  but I'm unsure how to do it. Laravel does all this many-to-many stuff magically behind the scenes.
Doing something like this will give an error (I'm trying to add foo: "bar" to every pivot)
public function brands()
{
  $brands = $this->belongsToMany('Brand'); 

  foreach($brands as $brand)
  {
    $brand->foo = 'bar';
  }

  return $brands;
}

A:

Since you are interested in modifying it JSON output you can override toArray() and add the property in there:
public function toArray(){
    foreach($this->brands as $brand){
        $brand->pivot->foo = 'bar';
    }
    return parent::toArray();
}

Update
To avoid unwanted loading of the brands relation. You can first get the array and check if the relationship has been loaded
public function toArray(){
    $array = parent::toArray();
    if(isset($array['brands'])){
        foreach($array['brands'] as &$brand){
            $brand['pivot']['foo'] = 'bar';
        }
    }
    return $array;
}

Note that I'm using & before $brand to pass the array in by reference and not only by value. Otherwise I would have to do $array['brands'][$index]['pivot']['foo'] = inside the loop.

