'json', 'phones' => Serialize::class, 'extra' => Serialize::class, ]; public static function boot() { parent::boot(); static::created(function ($model) { $model->stat()->create([]); }); } /** * User Stat: * * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function stat() { return $this->hasOne($this->modelClass('UserStat', 'Users'), 'user_id', 'user_id'); } /** * User groups * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function groups() { return $this->hasMany($this->modelClass('UserGroups', 'Users'), 'user_id', 'user_id'); } /** * Check if user is in group * * @param int|array $groupId * @return bool */ public function isInGroup($groupId) { return $this->groups()->whereIn('group_id', is_array($groupId) ? $groupId : func_get_args())->count() > 0; } /** * Add user to group * * @param int|array $groupId * @return int total groups added */ public function groupAdd($groupId) { $current = $this->groups()->get()->keyBy('group_id'); $create = array(); foreach ((array) $groupId as $id) { if (is_numeric($id) && $id && ! $current->get($id)) { $create[] = ['group_id' => $id]; } } if ($create) { return $this->groups()->createMany($create)->count(); } else { return 0; } } /** * Remove user from group(s) * * @param int|array $groupId * @return mixed */ public function groupRemove($groupId) { return $this->groups()->whereIn('group_id', (array)$groupId)->delete(); } /** * Remove user from all groups * * @return mixed */ public function groupRemoveAll() { return $this->groups()->delete(); } }