User.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Contracts\Auth\MustVerifyEmail;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Relations\HasMany;
  6. use Illuminate\Database\Eloquent\SoftDeletes;
  7. use Illuminate\Foundation\Auth\User as Authenticatable;
  8. use Illuminate\Notifications\Notifiable;
  9. use Illuminate\Support\Facades\DB;
  10. class User extends Authenticatable implements MustVerifyEmail
  11. {
  12. use HasFactory, Notifiable, SoftDeletes;
  13. const DEFAULT_SORT_BY = 'created_at';
  14. /**
  15. * The attributes that are mass assignable.
  16. *
  17. * @var list<string>
  18. */
  19. protected $fillable = [
  20. 'name',
  21. 'email',
  22. 'notification_email',
  23. 'phone',
  24. 'password',
  25. 'role',
  26. 'color',
  27. 'token_fcm',
  28. ];
  29. /**
  30. * The attributes that should be hidden for serialization.
  31. *
  32. * @var list<string>
  33. */
  34. protected $hidden = [
  35. 'password',
  36. 'remember_token',
  37. ];
  38. /**
  39. * Get the attributes that should be cast.
  40. *
  41. * @return array<string, string>
  42. */
  43. protected function casts(): array
  44. {
  45. return [
  46. 'email_verified_at' => 'datetime',
  47. 'password' => 'hashed',
  48. ];
  49. }
  50. /**
  51. * Route notifications for the FCM channel.
  52. *
  53. * @return string
  54. */
  55. public function routeNotificationForFcm(): string
  56. {
  57. return (string)$this->token_fcm;
  58. }
  59. public function getAppInstalledAttribute(): string
  60. {
  61. return $this->token_fcm ? 'Да' : 'Нет';
  62. }
  63. public function userNotifications(): HasMany
  64. {
  65. return $this->hasMany(UserNotification::class);
  66. }
  67. public function unreadUserNotifications(): HasMany
  68. {
  69. return $this->userNotifications()->whereNull('read_at');
  70. }
  71. public static function assignUniqueFcmToken(int $userId, string $token): void
  72. {
  73. DB::transaction(function () use ($userId, $token) {
  74. self::query()
  75. ->where('id', '!=', $userId)
  76. ->where('token_fcm', $token)
  77. ->update(['token_fcm' => null]);
  78. self::query()
  79. ->where('id', $userId)
  80. ->update(['token_fcm' => $token]);
  81. });
  82. }
  83. public static function clearFcmToken(int $userId): void
  84. {
  85. self::query()
  86. ->where('id', $userId)
  87. ->update(['token_fcm' => null]);
  88. }
  89. }