Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Entrust update user roles

Tags:

php

laravel-5

I create a role-based project with Laravel 5 and Entrust, everything works fine until I try to update a user's role list, the bloody "Integrity constraint violation" reminds me that when calling

$user->attachRoles($roles);

It does not delete the user's roles first, so I check the interfaces of usertrait,then come up with

$user->detachRoles($user->roles);
$user->attachRoles($roles);

The code looks pretty ugly, and I think there is three SQL been executed

  • find user's roles
  • delete the relations
  • add new relations

I was really hoping it would be like

$user->updateRoles($roles);

which can compare existing roles, and do some optimazation.

Am I missing something?

like image 662
Chris Peng Avatar asked Apr 20 '15 07:04

Chris Peng


Video Answer


1 Answers

You can use function $user->roles()->sync($roleKeys). It takes array of role keys and after executing all previous roles are deleted.

like image 80
Margus Pala Avatar answered Oct 03 '22 01:10

Margus Pala