User.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Modules\User\Models;
  3. use Catch\Base\CatchModel as Model;
  4. use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
  5. use Illuminate\Database\Eloquent\Casts\Attribute;
  6. use Laravel\Sanctum\HasApiTokens;
  7. use Modules\User\Models\Traits\UserRelations;
  8. use Illuminate\Auth\Authenticatable;
  9. /**
  10. * @property int $id
  11. * @property string $username
  12. * @property string $email
  13. * @property string $avatar
  14. * @property string $password
  15. * @property int $creator_id
  16. * @property int $status
  17. * @property string $login_ip
  18. * @property int $login_at
  19. * @property int $created_at
  20. * @property int $updated_at
  21. * @property string $remember_token
  22. */
  23. class User extends Model implements AuthenticatableContract
  24. {
  25. use Authenticatable, UserRelations, HasApiTokens;
  26. protected $fillable = [
  27. 'id', 'username', 'email', 'avatar', 'password', 'remember_token', 'creator_id', 'status', 'department_id', 'login_ip', 'login_at', 'created_at', 'updated_at', 'deleted_at'
  28. ];
  29. /**
  30. * @var array|string[]
  31. */
  32. public array $searchable = [
  33. 'username' => 'like',
  34. 'email' => 'like',
  35. 'status' => '='
  36. ];
  37. /**
  38. * @var string
  39. */
  40. protected $table = 'users';
  41. protected array $fields = ['id', 'username', 'email', 'avatar', 'creator_id', 'status', 'department_id', 'created_at'];
  42. /**
  43. * @var array|string[]
  44. */
  45. protected array $form = ['username', 'email', 'password', 'department_id'];
  46. /**
  47. * @var array|string[]
  48. */
  49. protected array $formRelations = ['roles', 'jobs'];
  50. /**
  51. * password
  52. *
  53. * @return Attribute
  54. */
  55. protected function password(): Attribute
  56. {
  57. return new Attribute(
  58. // get: fn($value) => '',
  59. set: fn ($value) => bcrypt($value),
  60. );
  61. }
  62. /**
  63. * is super admin
  64. *
  65. * @return bool
  66. */
  67. public function isSuperAdmin(): bool
  68. {
  69. return $this->{$this->primaryKey} == config('catch.super_admin');
  70. }
  71. /**
  72. * update
  73. * @param $id
  74. * @param array $data
  75. * @return mixed
  76. */
  77. public function updateBy($id, array $data): mixed
  78. {
  79. if (isset($data['password'])) {
  80. if (empty($data['password'])) {
  81. if (isset($data['password'])) {
  82. unset($data['password']);
  83. }
  84. } else {
  85. $data['password'] = bcrypt($data['password']);
  86. }
  87. } else{
  88. if (isset($data['password'])){
  89. unset($data['password']);
  90. }
  91. }
  92. return parent::updateBy($id, $data);
  93. }
  94. }