php - Laravel Update Many-to-Many Foreign Key Record -


i have user, role, , user_role table many-to-many relationship between user , role table.

class user extends model {     public function roles {         return $this->belongstomany('app\role');     } }  class role extends model {     public function users {         return $this->belongstomany('app\user');     } }  user - id - other_columns  role - id - other_columns  user_role - id - user_id - role_id - other_columns 

user_role can have multiple same record different role_user.id.

how update user's role without changing or deleting record of user_role table? or in other word how update user_role.role_id without changing or deleting user_role.id?

i have tried:

$user->roles()->updateexistingpivot($userroleid, ['role_id' => $newroleid]); 

and

$user->roles()->sync($userroleid, ['id' => $userroleid, 'role_id' => $newroleid, 'user_id' => $userid]); 

but don't work.

update

this code work, changes same other record.

$user->roles()->updateexistingpivot($oldroleid, ['role_id' => $newroleid]); 

and have tried filter first

$user->roles()->wherepivot('id', $userroleid)->updateexistingpivot($oldroleid, ['role_id' => $newroleid]); 

you can try updateexistingpivot()

$user->roles()->updateexistingpivot($roleid, ['role_id' => $newroleid]); 

if you're using more 1 pair of same user_id , role_id , want update 1 row, try use newpivotstatement():

$user->roles()->newpivotstatement()->where('id', $userroleid)->update(['role_id' => $newroleid]); 

and solution @yosua lijanto binar:

$user->roles()->wherepivot('id', $userroleid)->updateexistingpivot($oldroleid, ['role_id' => $newroleid]); 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -