I have a Many-to-Many-Relationship between the User and the Customview Model:
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* Customview relation
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function customviews ()
{
return $this->belongsToMany( Customview::class )->withPivot( 'default' );
}
}
Now, I want to update all the user's customview-assignments and reset their default flag to 0.
By hand this should look like this in SQL (the pivot table's name is customview_user):
UPDATE `customview_user` SET `default`=0 WHERE `user_id`=<user_id>;
Is there a way to do this like this:
$user->customviews()->...update(['default' => 0]);
There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.
Click Analyze > Refresh, or press Alt+F5. Tip: You can also refresh the PivotTable by right-clicking on the PivotTable, and then selecting Refresh. To update all PivotTables in your workbook at once, click Analyze > Refresh arrow > Refresh All.
01 Use Of Sync In Laravel The sync() method accepts an array as an argument. As the name suggests, this method synchronizes the database entries that means whatever you pass in this method, those records will be kept into the database and the rest will be removed from the intermediate(pivot) table.
You may have moved on from this, but for posterity I'll reply anyway as I found this question via Google.
It's hacky, but this does the trick:
$user->customviews()
->newPivotStatement()
->where('user_id', '=', $user->id)
->update(array('default' => 0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With