Skip to main content

Overview

The User model extends Laravel’s Authenticatable class and serves as the core authentication model for Health Manager. It includes role-based access control, user permissions, and self-provisioning admin functionality.

Namespace

App\Models\User

Class Declaration

class User extends Authenticatable

Database Schema

The users table includes the following columns:
id
bigint
required
Primary key, auto-incrementing
name
string
required
User’s full name
email
string
required
User’s email address (unique)
username
string
required
User’s unique username for login
password
string
required
Hashed password
role
string
default:"user"
User role (either ‘admin’ or ‘user’)
email_verified_at
timestamp
Email verification timestamp
remember_token
string
Remember me token for persistent sessions
created_at
timestamp
Record creation timestamp
updated_at
timestamp
Record last update timestamp

Fillable Attributes

These attributes can be mass assigned:
name
string
required
User’s full name
email
string
required
User’s email address
username
string
required
Unique username for authentication
password
string
required
User’s password (will be automatically hashed)
role
string
default:"user"
User role: ‘admin’ or ‘user’

Hidden Attributes

These attributes are automatically hidden from JSON serialization:
  • password
  • remember_token

Casts

[
    'email_verified_at' => 'datetime',
    'password' => 'hashed',
]

Relationships

allowedViewers()

Defines users who have permission to view this user’s health data.
public function allowedViewers()
{
    return $this->belongsToMany(User::class, 'user_permissions', 'owner_id', 'viewer_id');
}

accessibleUsers()

Defines users whose health data this user has permission to view.
public function accessibleUsers()
{
    return $this->belongsToMany(User::class, 'user_permissions', 'viewer_id', 'owner_id');
}

Methods

isAdmin()

Checks if the user has admin role.
return
bool
Returns true if user role is ‘admin’, false otherwise
public function isAdmin(): bool
{
    return $this->role === 'admin';
}
Example Usage:
$user = User::find(1);

if ($user->isAdmin()) {
    // Grant admin access
    echo "Welcome, administrator!";
}

canView()

Checks if the user can view a target user’s health data.
targetUserId
int
required
The ID of the user whose data access is being checked
return
bool
Returns true if user can view target user’s data
public function canView($targetUserId)
{
    return $this->id === $targetUserId ||
           $this->accessibleUsers()->where('owner_id', $targetUserId)->exists();
}
Example Usage:
$currentUser = auth()->user();
$targetUserId = 5;

if ($currentUser->canView($targetUserId)) {
    // User can view this data
    $measurements = MeasurementWeight::where('user_id', $targetUserId)->get();
}

Boot Method

The User model includes a boot method that automatically assigns the ‘admin’ role to the first user created in the system.
protected static function boot()
{
    parent::boot();

    static::creating(function ($user) {
        if (static::count() === 0) {
            $user->role = 'admin';
        }
    });
}

Usage Examples

Creating a New User

// First user becomes admin automatically
$admin = User::create([
    'name' => 'John Admin',
    'email' => '[email protected]',
    'username' => 'johnadmin',
    'password' => 'secure-password', // Will be hashed automatically
    'role' => 'user', // Will be overridden to 'admin' for first user
]);

// Subsequent users have 'user' role
$user = User::create([
    'name' => 'Jane Doe',
    'email' => '[email protected]',
    'username' => 'janedoe',
    'password' => 'secure-password',
]);

Managing User Permissions

// Grant viewer permission
$owner = User::find(1);
$viewer = User::find(2);

// Allow viewer to access owner's health data
$owner->allowedViewers()->attach($viewer->id);

// Check if viewer has access
if ($viewer->canView($owner->id)) {
    echo "Access granted";
}

// Get all users this viewer can access
$accessibleUsers = $viewer->accessibleUsers;

// Get all viewers for an owner
$viewers = $owner->allowedViewers;

// Revoke access
$owner->allowedViewers()->detach($viewer->id);

Checking Admin Status

$user = auth()->user();

if ($user->isAdmin()) {
    // Admin-only operations
    $allUsers = User::all();
} else {
    // Regular user operations
    $ownData = $user->accessibleUsers;
}

Authentication Example

// Login with username
if (Auth::attempt(['username' => 'johnadmin', 'password' => 'password'])) {
    $user = Auth::user();
    echo "Welcome, {$user->name}";
}

// Login with email
if (Auth::attempt(['email' => '[email protected]', 'password' => 'password'])) {
    $user = Auth::user();
    echo "Welcome, {$user->name}";
}

Traits Used

  • HasFactory - Enables model factories for testing and seeding
  • Notifiable - Adds notification functionality to users

Build docs developers (and LLMs) love