UserTrait.php 1.4 KB

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