User.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Http\Models;
  3. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  4. use Illuminate\Database\Eloquent\Relations\HasOne;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. use Illuminate\Notifications\Notifiable;
  7. use Illuminate\Foundation\Auth\User as AuthenticTable;
  8. class User extends AuthenticTable
  9. {
  10. use Notifiable, SoftDeletes;
  11. protected $table = 'users';
  12. protected $guarded = [];
  13. public function role(): HasOne
  14. {
  15. return $this->hasOne(
  16. Role::class,
  17. 'id',
  18. 'role_id'
  19. );
  20. }
  21. public function getStatusWithCssAttribute()
  22. {
  23. return ($this->status ?? 0) ?
  24. sprintf('<button type="button" class="btn btn-xs btn-primary">%s</button>', '启用') :
  25. sprintf('<button type="button" class="btn btn-xs btn-danger">%s</button>', '禁用');
  26. }
  27. public function sites(): BelongsToMany
  28. {
  29. return $this->belongsToMany(
  30. Site::class,
  31. 'user_has_sites',
  32. 'user_id',
  33. 'site_id'
  34. );
  35. }
  36. public function permissions()
  37. {
  38. return $this->belongsToMany(
  39. Permission::class,
  40. 'user_has_permissions',
  41. 'user_id',
  42. 'permission_id'
  43. );
  44. }
  45. protected static $permissions; //静态缓存
  46. public function hasAuth($auth): bool
  47. {
  48. if (!empty($this->is_super)) return true;
  49. if (self::$permissions === null) {
  50. $role = $this->role ?? null;
  51. if (!$role) return false;
  52. self::$permissions = $role->permissions->where('type', 2)->pluck('rule')->toArray();
  53. }
  54. if (in_array($auth, self::$permissions)) {
  55. return true;
  56. }
  57. return false;
  58. }
  59. public function username()
  60. {
  61. return $this->username ?? '';
  62. }
  63. public static function getUserList()
  64. {
  65. $userList = User::query()->pluck('nickname', 'id')->toArray()??[];
  66. return $userList;
  67. }
  68. }