Laravel 5 update all Pivot entries

laravel, laravel-query-builder, php, pivot, sql

Solution

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));

Problem

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]); ```

Original source