'Sync Records With Default Values in Pivot Tables, Call to undefined method syncWithPivotDefaults()
I just upgraded laravel 7
to laravel 8.30.1
and
I am trying to add the default value of pivot column object_model
of term_relationships
table using the newly introduced method [syncWithPivotDefaults][1]()
of laravel 8.2
ERROR
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::syncWithPivotDefaults()
Table structure of term_relationships
table
ID
object_id
term_id
object_model
created_at
updated_at
Code in PostController
$cat_ids = [1,2,3];
$post->categories()->syncWithPivotDefaults($cat_ids, ['object_model', 'App/Post']);
Relationship In Post Model
public function categories() {
return $this->belongsToMany(Term::class, 'term_relationships', 'object_id', 'term_id')
->where('taxonomy', 'category')
->withTimestamps();
}
Solution 1:[1]
The correct method name is syncWithPivotValues()
. The method-name had been changed from the PR before release. It is best to follow the offical change log so you know the final change: https://github.com/laravel/framework/blob/8.x/CHANGELOG-8.x.md#v8200-2020-12-22
More information on how to use this method is in the documentation: https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations
If you would like to insert the same intermediate table values with each of the synced model IDs, you may use the syncWithPivotValues method:
$user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Robin Bastiaan |