/**
  * Get all roles as collection.
  *
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function getRoles()
 {
     if (!$this->roles) {
         $this->roles = $this->grantedRoles()->get();
         $deniedRoles = $this->deniedRoles()->get();
         foreach ($deniedRoles as $role) {
             $deniedRoles = $deniedRoles->merge($role->descendants());
         }
         foreach ($this->roles as $role) {
             if (!$deniedRoles->contains($role)) {
                 $this->roles = $this->roles->merge($role->descendants());
             }
         }
         $this->roles = $this->roles->filter(function ($role) use($deniedRoles) {
             return !$deniedRoles->contains($role);
         });
     }
     return $this->roles;
 }
Example #2
0
 /**
  *
  */
 public function save()
 {
     if (empty($this->data)) {
         return;
     }
     if ($this->relation instanceof Relations\HasMany && is_array($this->data)) {
         if (is_numeric($this->data[0])) {
             $data = new Collection();
             foreach ($this->data as $key => $item) {
                 // $this->data[$key] = $this->related->baseModel->find($item);
                 $data->push($this->related->baseModel->find($item));
             }
         } else {
             $data = new Collection($this->data);
         }
         // detach any existing models and only save the selected ones
         $foreignKey = $this->relation->getPlainForeignKey();
         $current = $this->relation->getResults();
         if (!$current) {
             $this->relation->saveMany($data->toArray());
             return;
         }
         $all = $data->merge($current);
         foreach ($all as $item) {
             if ($keep = $data->find($item->getKey())) {
                 $this->relation->save($keep);
             } else {
                 $item->{$foreignKey} = null;
                 $item->save();
             }
         }
     } else {
         if ($this->relation instanceof Relations\BelongsToMany && is_array($this->data)) {
             if (is_numeric($this->data[0])) {
                 $this->relation->sync($this->data);
             }
         } else {
             /* If we have an id let's grab the model instance, otherwise assume we were given it */
             $this->data = is_numeric($this->data) ? $this->related->baseModel->find($this->data) : $this->data;
             parent::saveRelation($this->relation, $this->data);
         }
     }
 }