Overview
The User model represents system users including administrators, supervisors, and technicians. It extends Laravel’s Authenticatable class and integrates with Spatie’s permission system for role-based access control and Laravel Sanctum for API authentication.
Illuminate\Foundation\Auth\User
Traits Used
HasFactory - Enables model factories for testing
Notifiable - Enables notifications
HasRoles - Spatie permission package for role management
HasApiTokens - Laravel Sanctum for API token authentication
Fillable Fields
The following fields can be mass-assigned:
Email address of the user. Must be unique in the system.
Hashed password for authentication. Automatically hashed when set.
Phone number of the user. Optional field.
Current status of the user account. Uses the UserStatusEnum enum.Possible values:
activo - Active user
inactivo - Inactive user
suspendido - Temporarily suspended user
Foreign key reference to the users table. The user (usually an admin) who approved this user’s account.
Date and time when the user account was approved.
Hidden Fields
The following fields are hidden from JSON serialization:
protected $hidden = [
'password',
'remember_token',
];
Casts
The model automatically casts the following attributes:
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'estado' => UserStatusEnum::class,
'fecha_aprobacion' => 'datetime',
];
}
Relationships
Self-Referencing Relationships
aprobador
Returns the user who approved this user’s account.
$user = User::find(5);
$aprobador = $user->aprobador;
if ($aprobador) {
echo "Aprobado por: {$aprobador->name}";
}
Relationship Details:
- Type:
BelongsTo
- Related Model:
App\Models\User
- Foreign Key:
aprobado_por
usuariosAprobados
Returns all users that this user has approved.
$admin = User::find(1);
$usuariosAprobados = $admin->usuariosAprobados;
foreach ($usuariosAprobados as $usuario) {
echo $usuario->name;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\User
- Foreign Key:
aprobado_por
Has Many
sesionesMantenimiento
Returns all maintenance sessions where this user worked as a technician.
$tecnico = User::find(3);
$sesiones = $tecnico->sesionesMantenimiento;
foreach ($sesiones as $sesion) {
echo $sesion->fecha_inicio;
echo $sesion->duracion;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\SesionesMantenimiento
- Foreign Key:
tecnico_id
auditorias
Returns all audit log entries for actions performed by this user.
$user = User::find(1);
$auditorias = $user->auditorias;
foreach ($auditorias as $auditoria) {
echo $auditoria->accion;
echo $auditoria->created_at;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\Auditoria
- Foreign Key:
usuario_id
notificaciones
Returns all notifications sent to this user.
$user = User::find(1);
$notificaciones = $user->notificaciones;
foreach ($notificaciones as $notif) {
echo $notif->titulo;
echo $notif->mensaje;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\Notificacion
- Foreign Key:
usuario_id
calendarioMantenimientos
Returns all scheduled maintenance where this user is the assigned technician.
$tecnico = User::find(3);
$calendarios = $tecnico->calendarioMantenimientos;
foreach ($calendarios as $calendario) {
echo $calendario->fecha_programada;
echo $calendario->activo->articulo->modelo;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\CalendarioMantenimiento
- Foreign Key:
tecnico_asignado_id
reportes
Returns all reports filed by this user.
$user = User::find(5);
$reportes = $user->reportes;
foreach ($reportes as $reporte) {
echo $reporte->descripcion;
echo $reporte->estado;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\Reporte
- Foreign Key:
usuario_id
mantenimientosSupervisados
Returns all maintenance operations where this user is the supervisor.
$supervisor = User::find(2);
$mantenimientos = $supervisor->mantenimientosSupervisados;
foreach ($mantenimientos as $mant) {
echo $mant->activo->articulo->modelo;
echo $mant->estado;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\Mantenimiento
- Foreign Key:
supervisor_id
mantenimientosTecnicoPrincipal
Returns all maintenance operations where this user is the primary technician.
$tecnico = User::find(3);
$mantenimientos = $tecnico->mantenimientosTecnicoPrincipal;
foreach ($mantenimientos as $mant) {
echo $mant->tipo; // preventivo, correctivo, predictivo
echo $mant->descripcion;
}
Relationship Details:
- Type:
HasMany
- Related Model:
App\Models\Mantenimiento
- Foreign Key:
tecnico_principal_id
Usage Examples
Creating a New User
use App\Models\User;
use App\Enums\UserStatusEnum;
use Illuminate\Support\Facades\Hash;
$user = User::create([
'name' => 'Juan Pérez',
'email' => '[email protected]',
'password' => Hash::make('secret123'),
'telefono' => '+1234567890',
'estado' => UserStatusEnum::ACTIVO,
]);
Approving a User
$newUser = User::find(10);
$admin = auth()->user();
$newUser->aprobado_por = $admin->id;
$newUser->fecha_aprobacion = now();
$newUser->estado = UserStatusEnum::ACTIVO;
$newUser->save();
Assigning Roles (Spatie Permissions)
$user = User::find(1);
// Assign a role
$user->assignRole('supervisor');
// Check if user has role
if ($user->hasRole('supervisor')) {
echo "User is a supervisor";
}
// Assign multiple roles
$user->assignRole(['technician', 'supervisor']);
// Give direct permission
$user->givePermissionTo('edit maintenance');
// Check permission
if ($user->can('edit maintenance')) {
echo "User can edit maintenance";
}
Suspending a User
use App\Enums\UserStatusEnum;
$user = User::find(5);
$user->estado = UserStatusEnum::SUSPENDIDO;
$user->save();
echo $user->estado->label(); // "Suspendido Temporalmente"
Querying Users
// Get all active users
$activeUsers = User::where('estado', UserStatusEnum::ACTIVO)->get();
// Get users with specific role
$supervisors = User::role('supervisor')->get();
// Get technicians with pending maintenance
$tecnicosOcupados = User::whereHas('mantenimientosTecnicoPrincipal', function($query) {
$query->whereIn('estado', ['pendiente', 'en_proceso']);
})->get();
// Get users who haven't been approved
$pendingUsers = User::whereNull('aprobado_por')->get();
Getting User’s Workload
$tecnico = User::find(3);
// Count active maintenance assignments
$mantenimientosActivos = $tecnico->mantenimientosTecnicoPrincipal()
->whereIn('estado', ['pendiente', 'en_proceso'])
->count();
// Get upcoming scheduled maintenance
$proximosTrabajos = $tecnico->calendarioMantenimientos()
->where('fecha_programada', '>=', now())
->orderBy('fecha_programada')
->get();
echo "Mantenimientos activos: {$mantenimientosActivos}";
echo "Próximos trabajos: {$proximosTrabajos->count()}";
Authentication Examples
// Login
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
// Check if user is active
if ($user->estado !== UserStatusEnum::ACTIVO) {
Auth::logout();
return 'Account is not active';
}
}
// Generate API token (Sanctum)
$token = $user->createToken('api-token')->plainTextToken;
// Revoke all tokens
$user->tokens()->delete();
Getting User Statistics
$supervisor = User::find(2);
$stats = [
'mantenimientos_supervisados' => $supervisor->mantenimientosSupervisados()->count(),
'mantenimientos_completados' => $supervisor->mantenimientosSupervisados()
->where('estado', 'completado')->count(),
'usuarios_aprobados' => $supervisor->usuariosAprobados()->count(),
];
Database Schema
CREATE TABLE users (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
email_verified_at TIMESTAMP NULL,
password VARCHAR(255) NOT NULL,
telefono VARCHAR(255) NULL,
estado VARCHAR(255) DEFAULT 'activo',
aprobado_por BIGINT UNSIGNED NULL,
fecha_aprobacion DATETIME NULL,
remember_token VARCHAR(100) NULL,
created_at TIMESTAMP NULL,
updated_at TIMESTAMP NULL,
FOREIGN KEY (aprobado_por) REFERENCES users(id) ON DELETE SET NULL
);