Esempio n. 1
0
 /**
  * Make a collection of role ids from provided roles
  * 
  * @param string|array|\Illuminate\Support\Collection $roles A role or list of roles to add to user.
  * 
  * @return \Illuminate\Support\Collection
  * 
  * @throws RollerException
  */
 public static function makeRoleIds($roles)
 {
     $roles = Support::makeCollection($roles);
     return $roles->map(function ($role) {
         if (is_string($role)) {
             try {
                 $role = Role::whereName($role)->firstOrFail();
             } catch (ModelNotFoundException $e) {
                 $role = Role::create(['name' => $role]);
             }
         } elseif (!$role instanceof Role) {
             throw new RollerException('Provided role is not a string or Role instance');
         }
         return $role->id;
     });
 }
Esempio n. 2
0
 /**
  * Sync roles for this user.
  *
  * @param array|\Illuminate\Support\Collection $roleIds
  * @param null|array $resource
  *
  * @throws RollerException
  */
 private function syncRoles($roleIds, $resource = null)
 {
     $roleIds = Support::makeCollection($roleIds);
     // Query to remove all roles for current user
     $query = RRU::whereUserId($this->getKey());
     if ($resource) {
         $query->whereResourceType($resource['type'])->whereResourceId($resource['id']);
     }
     // Query to relate all roles to current user
     $data = [];
     foreach ($roleIds as $roleId) {
         $data[] = ['user_id' => $this->getKey(), 'role_id' => $roleId, 'resource_type' => $resource['type'], 'resource_id' => $resource['id']];
     }
     // Execute queries in a transaction
     $table = (new RRU())->getTable();
     DB::transaction(function () use($query, $table, $data) {
         $query->delete();
         DB::table($table)->insert($data);
     });
 }