UserTrait.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace Modules\ContentManage\Http\Controllers;
  3. use Catch\Base\CatchController;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\DB;
  6. use Modules\User\Models\User;
  7. trait UserTrait
  8. {
  9. // 当前登录用户
  10. protected $currentUser;
  11. /**
  12. * 获取当前登录用户
  13. * @return User
  14. */
  15. protected function getCurrentUser(): User {
  16. if(!$this->currentUser) {
  17. $this->currentUser = $this->getLoginUser();
  18. }
  19. return $this->currentUser;
  20. }
  21. /**
  22. * 当前用户的所有的角色标识的结合
  23. * @return Collection
  24. */
  25. protected function listUserRoles():Collection {
  26. return $this->getCurrentUser()->roles->pluck('identify');
  27. }
  28. /**
  29. * 当前用户是否是cp角色
  30. * @return bool
  31. */
  32. public function userIsCp():bool {
  33. return $this->listUserRoles()->contains('cp');
  34. }
  35. /**
  36. * 如果当前用户是cp角色,返回cp_name,否则返回null
  37. * @return string
  38. */
  39. public function getUserCpName():string|null {
  40. if($this->userIsCp()) {
  41. return DB::table('user_belong_to_cp')
  42. ->where([
  43. 'is_enabled' => 1,
  44. 'user_id' => $this->getCurrentUser()->id,
  45. ])->value('cp_name');
  46. } else {
  47. return null;
  48. }
  49. }
  50. }