Laravel 5 update all Pivot entries
Asked Answered
D

2

8

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]);
Degression answered 18/10, 2016 at 9:21 Comment(0)
P
17

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));
Pregnancy answered 15/3, 2017 at 10:49 Comment(2)
This is exactly how I did it then: $this->customviews()->newPivotStatement()->where( 'user_id', $this->id )->update( [ 'default' => 0 ] );Degression
What if I want to update some of the relations, not all? One way can be "including not updated relations also".Indecisive
L
-2

Try with updateExistingPivot like this:

$user->customviews()->updateExistingPivot($customviewId, ['default' => 0]);
Lithea answered 18/10, 2016 at 10:10 Comment(1)
This works only with one row. I want to update all of the relations which are related to the user..Degression

© 2022 - 2024 — McMap. All rights reserved.