User
App\Core\Models\User represents an account in Pulse Engine. Use it to find a player or staff member, read and update their identity, check account flags, work with roles and permissions, and access their tokens, notifications and linked sign-in providers.
| Detail | Value |
|---|---|
| Source | backend/app/Core/Models/User.php |
| Database table | users |
| Primary key | id, an auto-incrementing integer |
| Base class | Illuminate\Foundation\Auth\User |
| Permission guard | sanctum |
| Default authentication model | App\Core\Models\User, configurable through AUTH_MODEL |
| Deletion | Permanent deletion; this model does not use SoftDeletes |
The account model owns identity and authentication. Game balances and stats belong to App\Core\Models\PlayerStat and the economy service; plugin-specific features belong in plugin-owned storage.
This page covers every method declared in Pulse's User class, its fields and relationships, and the attached traits' account APIs. General Eloquent query and persistence methods are explained where needed; this is not a duplicate reference for every inherited Laravel framework method. Examples describe the current main implementation.
How to find a user
Use these examples inside a booted Pulse backend: a controller, service, plugin handler, or Laravel Tinker. They are PHP code, not terminal commands. Import the class in the PHP file where you use it:
use App\Core\Models\User;
Find by ID
use App\Core\Models\User;
$user = User::find(42);
if ($user !== null) {
$username = $user->username;
}
find($id) returns a User or null. Here 42 is an example account ID; use the ID you intend to look up. Calling new User(42) does not load account 42: Eloquent's constructor expects an array of attributes.
When the request should fail if the account is missing:
use App\Core\Models\User;
$user = User::findOrFail(42);
findOrFail() returns a User or throws ModelNotFoundException. Laravel normally renders that exception as HTTP 404 during a request.
Find by username or email
use App\Core\Models\User;
$byUsername = User::where('username', 'space_pilot')->first();
$byEmail = User::where('email', '[email protected]')->first();
Both return a User or null. Replace first() with firstOrFail() if absence should be an error. Case sensitivity follows your database collation; do not assume SQLite tests and MariaDB compare every string identically.
Get the signed-in user
In a controller method that receives Illuminate\Http\Request $request:
$user = $request->user();
On a route protected by auth:sanctum, the request has already passed the authentication check. On a public route, this can return null. Finding an account by ID and authenticating as that account are different operations: a lookup gives the caller no permission to act for it.
Query several users
use App\Core\Models\User;
$players = User::query()
->where('is_banned', false)
->with('roles')
->orderBy('id')
->paginate(25);
This returns a paginator, not one user. with('roles') loads the role relationship with the query. Pulse enables strict Eloquent behaviour outside production, including checks for missing selected attributes and lazy loading; load relationships deliberately.
Fields and stored values
A field existing in the database, being mass-assignable, and appearing in an API response are three separate things.
Identity and profile
| Field | Stored type / constraints | Mass-assignable? | Purpose |
|---|---|---|---|
id |
Unsigned big integer primary key | No | Account identifier. |
name |
String, up to 255 characters | Yes | Display name; required by the base schema. |
username |
Nullable string, up to 100; unique | Yes | Account handle. Public registration requires it even though the column permits null. |
email |
String, up to 255; unique | Yes | Sign-in and contact address. |
bio |
Nullable text | Yes | Profile text. Profile API limits input to 2,000 characters. |
timezone |
Nullable string, up to 100 | Yes | Stored profile preference. |
locale |
Nullable string, up to 20 | Yes | Stored profile preference. |
website_url |
Nullable string, up to 2,048 | Yes | Stored website value. The current profile validator checks string length, not URL format. |
profile_photo_path |
Nullable string, up to 2,048 | Yes | Avatar location. The avatar endpoint saves Storage::url($path) here. |
profile_picture also appears in $fillable and as an API resource fallback, but the current core migrations do not create that column. Writing it on a standard core database can fail with an unknown-column error. Use the avatar upload endpoint or profile_photo_path for the existing schema.
Authentication and account flags
| Field | Stored type / default | Mass-assignable? | Model behaviour |
|---|---|---|---|
password |
String | Yes | hashed cast hashes assigned plain-text passwords. Hidden from raw model serialization. |
remember_token |
Nullable string, up to 100 | No | Framework remember-me value. Hidden from raw serialization. |
email_verified_at |
Nullable timestamp | Yes | Cast to a date/time object. |
is_banned |
Boolean, default false; indexed |
Yes | Accessor returns a boolean, defaulting to false if the attribute is absent. |
force_password_change |
Boolean, default false |
Yes | Used by password-change handling; no explicit boolean cast in this model. |
two_factor_secret |
Nullable text | No | Encrypted secret written by TwoFactorAuthService. No model-level encrypted cast. |
two_factor_recovery_codes |
Nullable text | No | Encrypted recovery-code JSON written by the service. |
two_factor_confirmed_at |
Nullable timestamp | No | Presence is part of the enabled check; no explicit datetime cast in User. |
The User class implements the MustVerifyEmail interface. A verification timestamp alone does not mean verification is enforced on every route: the require_email_verification setting decides that. sendEmailVerificationNotification() sends the verify-email template in the player's language when the admin email settings are active, else the framework notification (see account emails in communication).
Activity and timestamps
| Field | Stored type | Mass-assignable? | Model behaviour |
|---|---|---|---|
last_active |
Nullable timestamp; indexed | Yes | Explicit datetime cast. Login and other application paths update it. Reading the model does not update it. |
last_login_at |
Nullable timestamp | Yes | Written with last_login_ip and last_active by CoreEvents::signedIn, only when a sign-in completes (password without 2FA, after 2FA verify, OAuth), never at the password step of a 2FA account; cast to datetime in User. |
last_login_ip |
Nullable string, up to 45 | Yes | Last recorded login address. |
created_at |
Nullable timestamp | No | Managed by Eloquent timestamps. |
updated_at |
Nullable timestamp | No | Managed by Eloquent timestamps. |
UserResource converts activity timestamps into ISO date strings independently of the model's casts. If writing backend code that needs a date object for an uncast timestamp, parse it explicitly rather than assuming the attribute is already Carbon.
Create, update and delete
These are inherited Eloquent operations. They do not perform HTTP validation or authorize the caller automatically.
User::create(array $attributes)
Creates and saves an account, then returns the new User. For normal public sign-up use POST /api/v1/register; it also validates input, assigns the ordinary role when available, attempts the welcome email and returns an authentication token.
For trusted backend code that intentionally creates an account directly:
use App\Core\Models\User;
$user = User::create([
'name' => 'Space Pilot',
'username' => 'space_pilot',
'email' => '[email protected]',
'password' => 'Local-example-password-42!',
]);
This writes a row. Use your own unique identity values and password. The model hashes the password and fires user.created; it does not assign a role, issue a token or send a welcome email by itself. Database uniqueness and required-column violations raise database exceptions. Supplying non-fillable attributes can raise a mass-assignment exception under Pulse's strict model settings.
$user->fill(array $attributes) and $user->save()
fill() changes allowed attributes in memory and returns the same model. save() persists changes and returns a boolean; database failures can throw exceptions.
In a controller method with an authenticated request, update only validated profile fields:
$validated = $request->validate([
'bio' => ['nullable', 'string', 'max:2000'],
]);
$user = $request->user();
$user->fill($validated);
$user->save();
This requires an authenticated route. It edits the requesting user's bio. Do not pass $request->all() into fill() or update(): this model's fillable list includes account flags and passwords as well as profile fields.
$user->update(array $attributes)
Combines fill and save for an existing model and returns a boolean. It has the same mass-assignment rules. To update another account through admin code, authorize the operation with UserPolicy first; the model does not perform that check.
$user->fresh() and $user->refresh()
| Method | Result |
|---|---|
fresh() |
A newly fetched model, or null if the row no longer exists; leaves the original object alone. |
refresh() |
Reloads this model and its loaded relationships, returning the same object; a missing persisted row can raise ModelNotFoundException. |
Use these after another operation changes the stored record. A relationship already loaded into $user->roles can otherwise remain stale.
$user->delete()
Deletes the account permanently. There is no soft-delete or restore API on this class. UserPolicy::delete() allows only an admin deleting a different, non-admin account. Calling the model directly does not enforce the policy.
Associated data follows each table's migration rules, not one universal cascade. For example, player_stats.user_id cascades and economy transaction sender/receiver references become null. Do not infer that deleting an account removes every related session, token or plugin record. Plugin-owned data needs an explicit retention and cleanup policy.
Methods declared by Pulse's User class
The following sections cover all nine methods declared in backend/app/Core/Models/User.php. Relationship methods are callable directly; lifecycle, casting and magic methods run through the framework.
oauthProviders(): HasMany
Returns the Eloquent relationship to App\Core\Models\OAuthProvider through oauth_providers.user_id.
Arguments: none. Returns: a HasMany query, not a collection until executed.
$links = $user->oauthProviders()->get();
$discord = $user->oauthProviders()->where('provider', 'discord')->first();
$links is a collection of provider links; $discord is a link or null. Eager-load with User::with('oauthProviders') before reading the $user->oauthProviders collection in strict environments.
The related model encrypts token and refresh_token, hides them from serialization, and casts expires_at to datetime. Provider linking/unlinking belongs to the OAuth controller and service; adding a row directly does not complete provider authentication.
notifications(): HasMany
Returns the relationship to Pulse's App\Core\Models\Notification using notifications.user_id. It overrides Laravel's normal polymorphic notification relationship from Notifiable.
Arguments: none. Returns: HasMany.
$unread = $user->notifications()->unread()->latest()->get();
$notification = $user->notifications()->find($notificationId);
if ($notification !== null) {
$notification->markAsRead();
}
Here $user is the account already authorized for this operation, and $notificationId is the notification to read. Querying through the relationship limits the lookup to that account. markAsRead() is a method on the related notification, not on User.
For creating Pulse notifications, use NotificationService:
use App\Core\Services\NotificationService;
$notification = app(NotificationService::class)->system(
$user,
'Profile updated',
'Your profile changes were saved.'
);
This creates a database record and returns a Pulse Notification. The service call shown does not itself send email or broadcast a WebSocket event. Do not assume Laravel's standard database-notification channel has the same storage contract.
hasTwoFactorEnabled(): bool
Checks whether two_factor_secret and two_factor_confirmed_at are both non-null.
Arguments: none. Returns: true only when both values are present; false if either is null or reading a missing attribute raises MissingAttributeException.
$enabled = $user->hasTwoFactorEnabled();
The method checks stored presence. It does not decrypt the secret, validate a one-time code, or confirm that recovery codes exist. A partially selected model may report false because required attributes were not loaded; fetch the full user before using this as an authentication decision.
Use TwoFactorAuthService and the /api/v1/2fa/* endpoints to set up and manage 2FA. The password login controller checks this method before issuing a token and instead returns a challenge when enabled. Calling $user->createToken() directly bypasses that login workflow.
getIsBannedAttribute(): bool
Accessor used whenever code reads $user->is_banned.
Arguments: none. Returns: the raw is_banned attribute converted to boolean, or false when absent.
$banned = $user->is_banned;
The fallback avoids strict missing-attribute errors, but it is not proof that an incompletely selected record is unbanned. Include is_banned in security-sensitive queries.
isBanned(): bool
Reads the same accessor through a named method.
Arguments: none. Returns: $user->is_banned as a boolean.
if ($user->isBanned()) {
// Choose the appropriate response for this operation.
}
It does not ban the account, revoke tokens or throw an exception. CheckUserBanned middleware rejects banned accounts on routes that use it; the admin ban controller also revokes all the target's personal access tokens.
The admin ban request accepts a duration, but the current controller logs that value and stores a boolean. It does not persist an expiry or schedule automatic unbanning. Do not promise a temporary ban from the boolean alone.
__call($method, $parameters)
PHP calls this for an instance method that has no accessible concrete implementation.
| Argument | Meaning |
|---|---|
$method |
Requested method name. |
$parameters |
Array of arguments supplied to that method. |
If a macro with that name exists, Pulse invokes it through macroCall(). Otherwise it delegates to the parent Eloquent implementation, which handles relationships, query forwarding and other dynamic behaviour. The return value and exceptions come from the selected target.
Call your intended method normally, for example $user->displayLabel(). Do not call __call() or the aliased macroCall() yourself. A genuinely unknown method can raise BadMethodCallException.
__callStatic($method, $parameters)
Static counterpart to __call(). If the name is registered as a macro, Pulse invokes macroCallStatic(); otherwise Eloquent handles the static call. This is why normal query calls such as User::where(...) still work.
Arguments have the same meanings as above. Returns and errors depend on the dispatched operation. A static macro has no user instance to use as $this; use instance calls for account-specific macros.
casts(): array — protected
Laravel calls this to obtain the model's cast definitions:
[
'email_verified_at' => 'datetime',
'password' => 'hashed',
'last_active' => 'datetime',
'is_banned' => 'boolean',
];
It accepts no arguments and is not a public application API. Eloquent additionally handles its own created_at and updated_at timestamps. Do not assume other date or boolean fields receive these casts.
booted(): void — protected, static
Registers a created model-event listener. After Eloquent inserts a new user, the listener checks whether the hook service is bound and then dispatches:
app('hook')->action('user.created', ['user' => $user]);
Arguments: none. Return: none. The class boots once per process/model lifecycle, not once per query. Application code does not call booted() manually.
This runs before registration code assigns the ordinary role or creates the sign-in token. It is an Eloquent created event, not an after-commit guarantee; a surrounding transaction may still roll back. Bulk query-builder inserts bypass model events.
React to user creation
Place this in an enabled plugin's hooks.php. Keep only one <?php opening tag if adding it to an existing file:
<?php
app('hook')->addAction('user.created', function (array $payload): void {
$user = $payload['user'];
logger()->info('Account created', [
'user_id' => $user->id,
'username' => $user->username,
]);
});
The payload contains the actual User object under user; it is not a bare user ID. The listener's return value does not replace the account. Registration code can also create accounts through admin tools or OAuth, so this event is broader than public sign-up. Core's class only dispatches user.created here; it does not dispatch user.updated or user.deleted from this model.
Roles, permissions and authorization
HasRoles supplies the role API and includes HasPermissions. The model uses the sanctum permission guard; the seeded roles are admin, moderator, game_master, lead_moderator, support_staff and user.
Check a role or permission
$isAdmin = $user->hasRole('admin');
$isStaff = $user->hasAnyRole(['admin', 'moderator']);
$canManageUsers = $user->hasPermissionTo('manage users');
The role or permission must exist for the correct guard. hasPermissionTo() can throw PermissionDoesNotExist for an undefined name; checkPermissionTo() returns false for that missing-permission case. A role name is not automatically a permission name. hasRole() answers a role question; policies and Gate answer whether this actor may perform a particular action on a particular target.
Role method reference
| Method | Arguments | Returns / effect |
|---|---|---|
roles() |
None | BelongsToMany role relationship. |
assignRole(...$roles) |
Role names, IDs, enums or role objects accepted by Spatie | Adds roles; returns this model. Does not remove existing roles. |
removeRole(...$role) |
Roles to remove | Removes matching assignments; returns this model. |
syncRoles(...$roles) |
Complete replacement role set | Replaces assignments; returns this model. An empty set removes all roles. |
hasRole($roles, ?string $guard = null) |
Role specification; optional guard | Boolean role match. |
hasAnyRole(...$roles) |
Accepted role specifications | True if any match. |
hasAllRoles($roles, ?string $guard = null) |
Required role set; optional guard | True if all match. |
hasExactRoles($roles, ?string $guard = null) |
Exact expected role set | True if the complete set matches. |
getRoleNames() |
None | Collection of role-name strings. |
role($roles, $guard = null, $without = false) |
Query scope arguments | Eloquent builder limited by roles; implemented by scopeRole(). |
withoutRole($roles, $guard = null) |
Query scope arguments | Builder excluding roles; implemented by scopeWithoutRole(). |
Changing role assignments does not authorize the caller. Use the role-management controller or your own explicit authorization before privileged mutations. Roles from a different guard can raise GuardDoesNotMatch; unknown roles can raise RoleDoesNotExist.
Permission method reference
| Method | Arguments | Returns / effect |
|---|---|---|
permissions() |
None | BelongsToMany direct-permission relationship. |
givePermissionTo(...$permissions) |
Permissions accepted by Spatie | Adds direct permissions; returns this model. |
syncPermissions(...$permissions) |
Complete direct-permission set | Replaces direct assignments; inherited role permissions remain. |
revokePermissionTo($permission) |
Permission to remove | Removes a direct assignment; returns this model. Does not remove permissions supplied by roles. |
hasPermissionTo($permission, $guardName = null) |
Name, ID, enum or permission object | Boolean check across direct and role permissions; undefined names may throw. |
checkPermissionTo($permission, $guardName = null) |
Same permission check | False instead of a missing-permission exception. |
hasAnyPermission(...$permissions) |
Permission list | Boolean: any effective permission matches. |
hasAllPermissions(...$permissions) |
Permission list | Boolean: all effective permissions match. |
hasDirectPermission($permission) |
Permission to check | Boolean direct-assignment check. |
hasAnyDirectPermission(...$permissions) |
Permission list | Boolean: any direct assignment matches. |
hasAllDirectPermissions(...$permissions) |
Permission list | Boolean: all direct assignments match. |
getDirectPermissions() |
None | Collection of directly assigned permission models. |
getPermissionsViaRoles() |
None | Collection of permissions supplied by roles. |
getAllPermissions() |
None | Collection combining effective permission models. |
getPermissionNames() |
None | Collection of directly assigned permission names. |
permission($permissions, $without = false) |
Query scope arguments | Builder limited by permissions; implemented by scopePermission(). |
withoutPermission($permissions) |
Query scope arguments | Builder excluding permissions; implemented by scopeWithoutPermission(). |
Spatie also exposes support methods used by the traits: bootHasRoles(), bootHasPermissions(), getRoleClass(), getPermissionClass(), getWildcardClass(), filterPermission($permission, $guardName = null), forgetCachedPermissions() and forgetWildcardPermissionIndex(). These manage trait booting, model resolution, permission normalization and caches. Normal account code uses the checks and mutations above; it does not call the boot methods manually.
User policy rules
AppServiceProvider registers UserPolicy for this model. Current admin controller operations apply these rules:
| Ability | Allowed actor and target |
|---|---|
viewAny, view |
Admin or moderator. |
create |
Admin only. |
update |
Admin/moderator editing another account; a moderator cannot edit an admin. Self-edits use account settings. |
delete |
Admin deleting another, non-admin account. |
ban |
Admin/moderator targeting another, non-admin account. Also used for unban. |
In a backend controller, before editing a different account:
use App\Core\Models\User;
use Illuminate\Support\Facades\Gate;
$target = User::findOrFail($targetId);
Gate::authorize('update', $target);
$targetId must come from your validated input or route parameter. Gate uses the authenticated actor and throws an authorization exception if denied, normally HTTP 403. Successfully querying a record does not bypass this step.
Personal access tokens
HasApiTokens supplies these methods. Tokens authenticate a user; Spatie roles and policies remain separate authorization checks.
Create a token
Only in trusted backend code after authenticating and authorizing the operation:
$issued = $user->createToken(
'local-tool',
['profile:read'],
now()->addDay()
);
$plainTextToken = $issued->plainTextToken;
$tokenId = $issued->accessToken->id;
Returns Laravel\Sanctum\NewAccessToken, containing the stored token model and its one-time plain-text token. The database stores a hash. Return the plain-text value only to the intended client; do not log it.
profile:read is an illustrative ability string, not a promise that Pulse's profile routes enforce this name. Abilities must be checked by the handler or middleware that consumes them. Creating a token does not verify a password, complete 2FA or test whether the account is banned.
Token method reference
| Method | Arguments | Returns / effect |
|---|---|---|
tokens() |
None | Polymorphic relationship to personal access token records. |
createToken(string $name, array $abilities = ['*'], ?DateTimeInterface $expiresAt = null) |
Label, abilities, optional expiry | NewAccessToken. Defaults grant all abilities if omitted. |
currentAccessToken() |
None | Token attached by authentication or withAccessToken(), or null; may be a transient token for session authentication. |
tokenCan(string $ability) |
Ability string | Boolean token-ability check. A newly loaded account without an attached token is not the authenticated request context. |
tokenCant(string $ability) |
Ability string | Inverse of tokenCan(). |
withAccessToken($accessToken) |
Token object | Attaches it to this model in memory and returns the model. Does not authenticate a request or create a DB token. |
generateTokenString() |
None | Generates the token's plain-text component; does not persist a token record. Normally used internally by createToken(). |
$user->tokens()->whereKey($tokenId)->delete() revokes a stored token belonging to that user. $user->tokens()->delete() revokes all their stored personal tokens. These do not by themselves clear every browser session record. Use the existing logout/session endpoints for their defined workflows.
Add a method from a plugin
Macroable allows a plugin to attach a method at runtime without changing User.php. Put this in the enabled plugin's hooks.php:
<?php
use App\Core\Models\User;
if (! User::hasMacro('displayLabel')) {
User::macro('displayLabel', function (): string {
return $this->username ?: $this->name;
});
}
Then, elsewhere in the booted backend after that plugin's hooks have loaded:
$label = $user->displayLabel();
Returns the account's username, falling back to its name. Use a normal closure rather than an arrow function that captures some unrelated outer $this.
| Method | Arguments | Returns / effect |
|---|---|---|
User::macro($name, $macro) |
Method name and callback/callable | Registers or replaces a runtime macro. |
User::hasMacro($name) |
Method name | Boolean: whether that name has been registered. |
User::mixin($mixin, $replace = true) |
Object supplying macro methods; whether to replace existing names | Registers methods from the mixin; reflection failures can throw. |
User::flushMacros() |
None | Clears all macros on this class. Useful in isolated tests; do not use to remove only your plugin's macro. |
Macros live in PHP process memory, not the database, and need registering when the application boots. A macro cannot override an already callable concrete PHP method because __call() runs only for unresolved calls. A macro is a callable method, not automatically a model attribute or JSON field: $user->displayLabel() does not create $user->displayLabel or append it to UserResource.
Store plugin-specific user data
The model file imports HasPluginMetadata at namespace level, but does not apply the trait inside the class. Therefore these are not built-in methods on the current core User: getPluginMeta(), setPluginMeta(), pluginMetadata(), or the trait's metadata query scopes. A plugin could supply extra macros, but their availability would be plugin-dependent.
Use the actual metadata model from trusted plugin backend code:
use App\Core\Models\PluginMetadata;
PluginMetadata::setValue($user, 'my-plugin', 'preferred_colour', 'blue');
$colour = PluginMetadata::getValue($user, 'my-plugin', 'preferred_colour', 'grey');
$user must be an existing, saved account. setValue() returns the stored PluginMetadata model; getValue() returns the stored JSON-compatible value or the supplied default. These calls do not require User to use the trait. They do not authorize who may edit the account; enforce that in your handler.
Use a slug belonging to your plugin and keep its records separate. Do not add game-specific columns to users. Metadata increments use a read/modify/write sequence and are not a substitute for locked economy transactions. Use EconomyService for money and ledger operations.
Other inherited account features
Notification delivery
Notifiable contributes notify($instance), notifyNow($instance, ?array $channels = null) and routeNotificationFor($driver, $notification = null). These route Laravel notification objects through the framework. notify() may queue delivery if the notification is queueable; notifyNow() sends immediately. They are not aliases for Pulse's NotificationService::create().
readNotifications() and unreadNotifications() are inherited query helpers, while the notifications() relationship itself is overridden by Pulse. For Pulse records, the explicit examples above use the Pulse relation and its read() / unread() scopes.
Factories
HasFactory provides User::factory($count = null, $state = []). Laravel currently resolves this model to Database\Factories\Core\Models\UserFactory, which sets name, username, email, hashed password and last activity. The PHPDoc annotation naming Database\Factories\UserFactory does not override runtime factory discovery. Both factory files exist; only the root factory declares an unverified() method.
use App\Core\Models\User;
$user = User::factory()->state(['email_verified_at' => null])->make();
make() returns an unsaved model; create() would persist it and fire model events. The explicit state above works with the selected factory; User::factory()->unverified() is not supported by that factory. Factory creation does not automatically assign roles. Use factories for development and tests, not public account provisioning. See test factory selection and the factory source.
Framework authentication helpers
The base authenticatable user provides framework identity and password interfaces, Gate authorization helpers such as can() / cannot(), and password-reset/verification support. These are inherited Laravel behaviour, not custom Pulse methods. Their availability does not mean every Pulse route uses every workflow. The controller, route middleware, policy and service together define the actual operation.
User API and output
These are existing backend routes, not methods on User. Prefix all paths below with /api/v1.
| Operation | Route | Relevant behaviour |
|---|---|---|
| Public registration | POST /register |
Validates, creates account, ordinary role if present, welcome-email attempt, token; 201. |
| Password login | POST /login |
Email/username lookup, password and ban checks, activity update; token or 2FA challenge. |
| Current account | GET /user |
Authenticated response through UserResource. |
| Profile changes | PATCH /user or PATCH /user/profile |
Validated profile-field allowlist. |
| Username change | POST /user/username |
Separate legacy handler; validator permits 255 while the core column is 100. Prefer profile endpoint's 100-character limit. |
| Avatar upload | POST /user/avatar |
Image upload, max 2,048 KB, writes profile_photo_path. |
| Password change | POST /user/change-password |
Password validation and force-change handling; clears the flag. |
| Sessions | GET /user/sessions |
Reports session rows and personal access tokens; these are distinct stores. |
| Tokens | GET, POST /user/api-tokens; DELETE /user/api-tokens/{token} |
List/create/revoke personal tokens; deletion endpoint rejects revoking its current token. |
| Logout | POST /logout |
Revokes the current stored token in this handler. |
| Logout all | POST /logout-all |
Revokes all stored personal tokens. |
| 2FA | /2fa/status, /2fa/setup, /2fa/confirm, /2fa/verify, /2fa/disable, /2fa/recovery-codes, /2fa/regenerate-recovery-codes |
Status is GET; the other listed operations are POST. /verify is the public challenge-verification endpoint. |
| OAuth | /oauth/* |
Provider discovery, redirect/callback/completion and authenticated account linking. |
| Admin account management | /admin/users/* |
Admin/moderator route gate plus operation-specific UserPolicy. |
/auth/register, /auth/login and /auth/logout are aliases in the same versioned API. Authenticated account routes use auth:sanctum and user.banned; plugin-owned routes must select their own required protections. A middleware alias being registered does not attach it to every route.
Use UserResource for API responses
In a backend handler after establishing which account the caller may view:
use App\Core\Http\Resources\UserResource;
return new UserResource($user->load(['roles', 'permissions', 'oauthProviders']));
The resource returns identity, profile, activity, account flags and timestamps. It computes two_factor_enabled and converts dates for JSON. Relationships appear only when loaded: roles contains role names, permissions contains direct permission names, and oauth_providers contains provider names. Use getAllPermissions() in backend logic when you need role-derived permissions too.
The username output falls back to name if the raw attribute is missing or null. avatar falls back from profile_photo_path to the legacy profile_picture attribute.
Raw model serialization is different. The current $hidden list contains only password and remember_token; it does not hide the 2FA fields or last_login_ip. Returning $user or $user->toArray() can expose attributes excluded by UserResource. The current admin controller has raw-model response paths, so do not assume all existing responses share the resource's allowlist. Examples here use the resource for controlled account output.
Current implementation limits
A handbook must distinguish working interfaces from names or comments left in the code:
profile_pictureis fillable but has no column in the standard migrated schema.HasPluginMetadatais imported but not used as a trait onUser.- The model has no
profile()orstats()relationship. Query the actual corePlayerStatmodel byuser_idfor stats. The 2FA verification controller currently attemptsload(['profile', 'roles']), so that response path needs a separate code fix before it can be relied on in a standalone core install. hasTwoFactorEnabled()andisBanned()are state checks with missing-attribute fallbacks. Fetch complete account data for authentication decisions.- Creating/updating a
Userdoes not apply request validators or authorize the caller. - Creating tokens directly does not perform Pulse's password/2FA/ban workflow.
- Neither a boolean ban nor the model's activity fields provide scheduling or presence by themselves.
These are observed boundaries of the current code. This reference does not change those behaviours.
Source map and verification
| Subject | Source |
|---|---|
| Model, fields, casts, methods and hook dispatch | User.php |
| Base account schema | create_users_table (backend/database/migrations/0001_01_01_000000_create_users_table.php) |
| Username and activity additions | add_last_active_to_users_table (backend/database/migrations/2026_03_01_100000_add_last_active_to_users_table.php) |
| Profile fields | create_user_settings_and_profile_fields (backend/database/migrations/2026_07_04_140000_create_user_settings_and_profile_fields.php) |
| 2FA columns | add_two_factor_columns (backend/database/migrations/2026_01_27_213740_add_two_factor_columns_to_users_table.php) |
| Password-change flag | backend/database/migrations/2026_02_03_154136_add_force_password_change_to_users_table.php |
| Login timestamp/IP fields | backend/database/migrations/2026_02_04_100004_add_last_login_to_users_table.php |
| Resource output | UserResource.php |
| Authentication and profile handlers | backend/app/Core/Http/Controllers/AuthController.php, UserSettingsController.php; backend/routes/api.php |
| Policy and admin operations | backend/app/Core/Policies/UserPolicy.php; backend/app/Core/Http/Controllers/Admin/UserManagementController.php |
| 2FA workflow | backend/app/Core/Services/TwoFactorAuthService.php; backend/app/Core/Http/Controllers/Auth/TwoFactorAuthController.php |
| Plugin metadata | backend/app/Core/Traits/HasPluginMetadata.php; backend/app/Core/Models/PluginMetadata.php |
| Related records | backend/app/Core/Models/Notification.php, OAuthProvider.php; backend/app/Core/Services/NotificationService.php |
| Authentication configuration | backend/config/auth.php, sanctum.php, permission.php |
| Trait implementations | Installed laravel/sanctum, spatie/laravel-permission, Laravel Macroable, notification and factory traits; versions locked by backend/composer.lock |
Verified against the checked-out source on 23 October 2026. Database fields were inspected after running core migrations against isolated SQLite :memory:. Account lookup, password hashing, profile persistence, flag checks, metadata calls, macros, role/permission checks, token abilities, notifications, user resource filtering and the creation-hook payload were exercised in that isolated environment. No development account or database was changed. This is backend verification; it does not establish browser behaviour or MariaDB parity.