Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 update all Pivot entries

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]);
like image 865
Daniel Leicht Avatar asked Oct 18 '16 09:10

Daniel Leicht


People also ask

How do I update pivot table in Laravel?

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.

How do I update a pivot table after changing data?

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.

What is sync in Laravel?

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.


1 Answers

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));
like image 200
lexilya Avatar answered Oct 10 '22 06:10

lexilya