update pivot table in case of many to many relation laravel4

Sameer picture Sameer · Mar 25, 2013 · Viewed 17.6k times · Source

I have started working with Laravel4 recently. I am facing some problem while updating pivot table data, in case of many to many relation.

The situation is: I have two table: Product, ProductType. The relation between them is Many to many. My Models are

class Product extends Eloquent {
    protected $table = 'products';
    protected $primaryKey = 'prd_id';

    public function tags() {
        return $this->belongsToMany('Tag', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

class Tag extends Eloquent {
    protected $table = 'tags';
    protected $primaryKey = 'tag_id';
        public function products()
    {
    return $this->belongsToMany('Product', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

While inserting data to the pivot table prd_tags, I did:

$product->tags()->attach($tag->tagID);

But now I want to update data in this pivot table, what is the best way to update data to the pivot table. Let's say, I want to delete some tags and add new tags to a particular product.

Answer

Andrew picture Andrew · Feb 21, 2014

Old question, but on Nov 13, 2013, the updateExistingPivot method was made public for many to many relationships. This isn't in the official documentation yet.

public void updateExistingPivot(mixed $id, array $attributes, bool $touch)

--Updates an existing pivot record on the table.

As of Feb 21, 2014 you must include all three arguments.

In your case, (if you wanted to update the pivot field 'foo') you could do:

$product->tags()->updateExistingPivot($tag->tagID, array('foo' => 'value'), false);

Or you can change the last boolean false to true if you want to touch the parent timestamp.

Pull request:

https://github.com/laravel/framework/pull/2711/files