Skip to main content

Overview

The User model extends Laravel’s Authenticatable class and implements email verification. It represents all users in the system including administrators, nutritionists, and patients. Namespace: App\Models\User Extends: Illuminate\Foundation\Auth\Authenticatable Implements: Illuminate\Contracts\Auth\MustVerifyEmail Traits:
  • HasFactory - Factory support for testing
  • Notifiable - Laravel notification support
  • TwoFactorAuthenticatable - Two-factor authentication from Laravel Fortify

Fillable Attributes

name
string
required
Full name of the user
email
string
required
Email address for authentication and communication
email_verified_at
datetime
Timestamp when the email was verified
password
string
required
Hashed password (automatically hashed via cast)
role_id
integer
required
Foreign key to the Role model (administrador, nutricionista, paciente)
user_state_id
integer
required
Foreign key to the UserState model (1 = activo, 2 = inactivo)
Whether the user has consented to data processing
Timestamp when data consent was granted

Hidden Attributes

The following attributes are automatically hidden from JSON serialization:
  • password
  • two_factor_secret
  • two_factor_recovery_codes
  • remember_token

Relationships

BelongsTo

role()
BelongsTo
Returns the user’s role (Role model)
$user->role()->where('name', 'nutricionista')->first();
userState()
BelongsTo
Returns the user’s current state (UserState model)
$user->userState; // Accesses the user_state_id relationship

HasOne

personalData()
HasOne
Returns the user’s personal data (PersonalData model)Note: This relationship is always eager-loaded via $with = ['personalData']
$user->personalData; // Always available without extra query
nutricionistaSettings()
HasOne
Returns nutritionist-specific settings (NutricionistaSettings model)Only applicable for users with the nutricionista role

HasMany

appointmentsAsPaciente()
HasMany
Returns appointments where the user is the patient
$user->appointmentsAsPaciente()->where('appointment_state_id', 1)->get();
appointmentsAsNutricionista()
HasMany
Returns appointments where the user is the nutritionist
$nutritionist->appointmentsAsNutricionista()->upcoming()->get();
attentionsAsPaciente()
HasMany
Returns clinical attentions where the user is the patient
attentionsAsNutricionista()
HasMany
Returns clinical attentions where the user is the nutritionist
schedules()
HasMany
Returns the nutritionist’s availability schedules (NutricionistaSchedule model)Only applicable for users with the nutricionista role

Helper Methods

Role Helpers

public function isAdmin(): bool
Returns true if the user has the ‘administrador’ role.
if ($user->isAdmin()) {
    // Grant admin access
}

public function isNutricionista(): bool
Returns true if the user has the ‘nutricionista’ role.
if ($user->isNutricionista()) {
    // Show nutritionist dashboard
}

public function isPaciente(): bool
Returns true if the user has the ‘paciente’ role.

State Helpers

public function isActive(): bool
Returns true if the user’s state is active (user_state_id === 1).
public function isInactive(): bool
Returns true if the user’s state is inactive (user_state_id === 2).

Clinical Eligibility

public function estaHabilitadoClinicamente(): bool
Determines if the user is eligible for clinical attention. A user is eligible when:
  • Their state is active (user_state_id === 1)
  • Their email is verified
This method centralizes eligibility logic to avoid repetition in views and controllers.
if ($user->estaHabilitadoClinicamente()) {
    // Allow appointment booking
} else {
    $reason = $user->motivoInhabilitacion();
    // Show error message with reason
}

public function motivoInhabilitacion(): ?string
Returns the reason why the user is NOT clinically eligible, or null if they are eligible. Possible return values:
  • "Usuario inactivo" - User state is inactive
  • "Email no verificado" - Email has not been verified
  • null - User is clinically eligible

Profile Helpers

public function initials(): string
Generates user initials from their name (first letter of first two words).
$user->name = "Juan Carlos Pérez";
echo $user->initials(); // "JC"

public function profilePhotoUrl(): ?string
Returns the full URL to the user’s profile photo, or null if not set.
$photoUrl = $user->profilePhotoUrl();
if ($photoUrl) {
    echo "<img src='{$photoUrl}' alt='Profile' />";
}

Notification Methods

public function sendEmailVerificationNotification(): void
Sends a custom email verification notification using App\Notifications\VerifyEmailNotification.
public function sendPasswordResetNotification(string $token): void
Sends a custom password reset notification using App\Notifications\ResetPasswordNotification.

Usage Examples

Creating a New Patient

use App\Models\User;
use Illuminate\Support\Facades\Hash;

$user = User::create([
    'name' => 'María González',
    'email' => '[email protected]',
    'password' => Hash::make('password123'),
    'role_id' => 3, // paciente
    'user_state_id' => 1, // activo
    'data_consent' => true,
    'data_consent_at' => now(),
]);

$user->sendEmailVerificationNotification();

Checking User Eligibility

$user = User::find(1);

if (!$user->estaHabilitadoClinicamente()) {
    return redirect()->back()->with('error', $user->motivoInhabilitacion());
}

// Proceed with appointment booking

Loading User with Relationships

// PersonalData is always loaded automatically
$user = User::find(1);
$age = $user->personalData->age;

// Load additional relationships
$user = User::with([
    'appointmentsAsPaciente.nutricionista',
    'attentionsAsPaciente.attentionData'
])->find(1);

Role-Based Authorization

if ($user->isNutricionista()) {
    $settings = $user->nutricionistaSettings;
    $schedules = $user->schedules;
    // Configure nutritionist dashboard
}

if ($user->isPaciente()) {
    $appointments = $user->appointmentsAsPaciente;
    // Show patient appointment history
}

Build docs developers (and LLMs) love