*/ use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var list */ protected $fillable = [ 'name', 'email', 'password', 'is_protected', 'two_factor_secret', 'two_factor_recovery_codes', 'two_factor_confirmed_at', ]; /** * Get the roles for the user. */ public function roles() { return $this->belongsToMany(Role::class); } /** * Check if the user has a specific role. */ public function hasRole(string $role): bool { return $this->roles()->where('slug', $role)->exists(); } /** * Check if the user has a specific permission. */ public function hasPermission(string $permission): bool { if ($this->hasRole('admin')) { return true; } return $this->roles()->whereHas('permissions', function ($query) use ($permission) { $query->where('slug', $permission); })->exists(); } /** * The attributes that should be hidden for serialization. * * @var list */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', 'is_protected' => 'boolean', 'two_factor_confirmed_at' => 'datetime', ]; } /** * Boot the model. */ protected static function boot() { parent::boot(); static::deleting(function ($user) { if ($user->is_protected) { throw new \Exception("The protected user '{$user->email}' cannot be deleted."); } }); static::updating(function ($user) { if ($user->is_protected && $user->isDirty(['email', 'is_protected'])) { throw new \Exception("The protected user '{$user->email}' cannot have critical fields modified."); } }); } }