DEV Community

Cover image for Sync Update Pivot (SyncWithPivotValues) In Laravel 9
Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Sync Update Pivot (SyncWithPivotValues) In Laravel 9

We often use to write Many-to-Many relationships and have new columns created in the generated table. So how can we add values ​​to the added columns and update it?
Example
Product many-to-many Language
Product Model: I have created new columns to add to the table " product_language " (title,keyword,description,slug,body)

public function languages(){
        return $this->belongsToMany("App\Models\Language","product_language","product_id","language_id")->withPivot('title','slug', 'keyword', 'description', 'body')
        ->withTimestamps();;
    }
Enter fullscreen mode Exit fullscreen mode

Language Model: (id,code)

public function products(){
        return $this->belongsToMany('App\Models\Product','product_language','product_id','language_id');
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)