User
class User extends Model implements Principal
Base user model. Holds the columns and behavior the framework relies on so Core never depends on the application's user model directly.
Applications extend this class (App\Models\Users by default) to add columns, relations, or override validation.
Framework code should resolve the concrete class with Auth::userModel() rather than calling static methods on this class. Static finders resolve against the class they are called on, so User::findById() would hydrate a base User instead of the application's subclass.
Traits
Creates the $created_at and $updated_at fields and performs the operation that updates timestamps.
Default implementation of the IsPrincipal contract, reading values off public model properties by their configured column names. A model satisfies the contract by using this trait and declaring properties matching the configured column names; the identifier, password, and remember-me token are then resolved dynamically from those properties.
This trait contains a collection of getter functions for retrieving values regarding your password policy.
Supports ability to validate console input.
Read-time date casting and JSON serialization for models.
Constants
| BLACKLIST |
Constant for blacklist. |
| WHITELIST |
Constant for whitelist. |
| whiteList |
|
| profileFields |
Columns a user may change on their own profile, and an admin may change
on the user edit page. Username, password, ACLs and status flags each
have their own flow and are never accepted from these forms. Extend
this list in the application's user model to make added columns
editable. |
| passwordFields |
The only column password reset and password change forms may assign. The confirm and current_password fields are read separately. |
| hidden |
|
| blackList |
Columns that may never be mass-assigned. Model::assign() prefers
whiteList when both are defined. |
Properties
| protected array | $errors | An array of errors. |
from HasValidators |
| protected string | $fieldName | The name of the field to be validated. |
from HasValidators |
| protected array | $reservedKeywords | An array of reserved keywords. |
from HasValidators |
| protected array | $reservedSQLKeyWords | from HasValidators | |
| protected array | $validators | Array of validator callbacks. |
from HasValidators |
| static private array | $emptyDates | Values treated as "no date". |
from HasCasts |
| static private array | $dateCastTypes | Cast types this trait understands. |
from HasCasts |
| static protected DB | $_db | The instance of the DB class. |
from Model |
| int | $id | ||
| protected string | $_modelName | The name of the model. |
from Model |
| static protected bool | $_softDelete | User records are soft deleted. |
|
| static protected string | $_table | ||
| protected bool | $_validates | Flag to indicate if validation is successful. |
from Model |
| string | $created_at | Time record was created. |
from HasTimestamps |
| string | $updated_at | Time record was updated. |
from HasTimestamps |
| protected string | $authIdentifierName | The name of the column holding the principal's unique identifier. |
from IsPrincipal |
| protected string | $authPasswordName | The name of the column holding the principal's hashed password. |
from IsPrincipal |
| protected string|null | $rememberTokenName | The name of the column holding the remember-me token, or null to disable remember-me for the model. Override getRememberTokenName() to change this per model. |
from IsPrincipal |
| protected array<string,string> | $casts | Columns converted when the model is serialized with toArray() or json_encode(). |
|
| string|null | $description | ||
| string|null | |||
| string|null | $fname | ||
| string|null | $lname | ||
| string|null | $username | ||
| string | $acl | The users currently assigned acls. |
|
| protected bool | $changePassword | Flag to set mode for being able to change a password. When true then the password can be changed or reset. Default value is false. |
|
| string|null | $confirm | Users must support the $confirm variable name contract for the confirm field. |
|
| int | $deleted | Set default value for db field. |
|
| int | $inactive | Inactive status flag. |
|
| int | $login_attempts | Login attempts counter. |
|
| string|null | $password | The password field. |
|
| int | $reset_password | The reset_password flag. When set to 1 the user is asked to set a new password. |
Methods
Adds a new error message to the $errors array.
Enforce rule where input must contain only alphabetic characters.
Enforce rule where input must be alphanumeric characters.
Ensures input is between within a certain range in length.
Checks if class exists within the specified namespace.
Tests form validation with multiple fields. Used by the unique validator to test several fields for uniqueness.
Enforce rule where response and $match parameter needs to be different.
Sets name of field to be validated.
Supports includeDeleted feature for database operations.
Checks if a port on a particular host is in use. Assists in verifying if a port is available for a serve command. If the port is already in use an error message is presented to the user.
Ensure user inputs valid comma separated list of values. The user must provide the following in the $attributes parameter: 1) Class containing full namespaced path 2) Name of function that returns an array of strings or a comma separated array of strings.
Enforces rule when input must contain at least one lower case character.
Enforce rule where response and $match parameter needs to match.
Ensures input meets requirements for maximum allowable length.
Ensures input meets requirements for minimum allowable length.
Enforces rule when input must contain no special characters.
Enforce rule when reserved keywords should be avoided.
Enforce rule when reserved SQL keywords should be avoided.
Enforces rule when input must contain at least one numeric character.
Enforce rule where input must contain only numeric characters.
Parse array containing additional validators or attributes for FrameworkQuestion as strings along with any additional parameters that maybe expected.
Adds validator to array of validators to be used.
Enforces rule when input must contain at least one special character.
Split on commas (tolerate spaces), normalize to lowercase, drop empties.
Checks if value already exists in a database.
Enforces rule when input must contain at least one lower case character.
Calls validator callbacks. This function also ensures validators don't bleed into next question if instance is reused.
Returns the casts for this model. Override to declare casts with a method instead of the $casts property.
Returns an attribute as a Carbon instance in the application timezone.
Converts a raw value into a Carbon instance according to a cast type.
Formats a datetime for JSON. Override to change the wire format for every datetime cast on a model that has no explicit :format.
Returns only public properties, exactly what json_encode() exposed before this trait existed. Called from outside class scope so protected and private properties are excluded.
Update the object with an associative array.
Implements beforeSave function described in Model parent class.
Retrieves number of rows affected or returned by the last query. This is a wrapper function for the DB::count function.
Gets an associative array of field values for insert or updating.
Wrapper for the find function that is found in the DB class.
Retrieves list of all records within a table related to a user.
Performs a database query against a specified table using the same query-building logic as the default find method.
Wrapper for the findFirst function that is found in the DB class.
Returns number of records in a table. A wrapper function for findTotal function in DB class.
Checks if results of validation is true or false. If false, the $this->_validates boolean instance variable is set to false. There are two ways to provide parameters for validation. You can pass the results from chaining functions and use just one parameter. Or you can provide the value of the field's name attribute, an array of validators, and a value for how you want the name of the field represented in error messages. If this value is not provided then the name attribute is used in messaging.
Wrapper for update and insert functions. A failed form validation will cause this function to return false.
Adds to the conditions to avoid getting soft deleted rows returned
Projects model rows into a [value => label] options map for form controls.
Updates one or more rows in this model's underlying table using your framework's params-style conditions.
Performs validation on user related forms.
Remember-me tokens are stored per device in the user_sessions table, not on the users row.
Reads a boolean password setting.
Reads a numeric password setting.
Returns the user's assigned ACLs as an array.
Assists in setting value of inactive field based on POST.
Assists in setting value of reset_password field based on POST.
Checks if the user has a specific ACL assigned.
Setter function for $changePassword.
To be called within beforeSave().
Retrieves a list of all users except current logged in user.
Finds user by username in the users table.
Details
in
HasValidators at line 127
void
addErrorMessage(string $message)
Adds a new error message to the $errors array.
in
HasValidators at line 137
HasValidators
alpha()
Enforce rule where input must contain only alphabetic characters.
in
HasValidators at line 151
HasValidators
alphaNumeric()
Enforce rule where input must be alphanumeric characters.
in
HasValidators at line 169
HasValidators
between(array $range)
Ensures input is between within a certain range in length.
in
HasValidators at line 194
HasValidators
classExists(string|array $namespace)
Checks if class exists within the specified namespace.
in
HasValidators at line 209
HasValidators
colonNotation()
Ensures response is in colon notation format.
in
HasValidators at line 231
void
compositeFieldValidation(array|string $additionalFieldData, array $conditions, array $bind)
Tests form validation with multiple fields. Used by the unique validator to test several fields for uniqueness.
in
HasValidators at line 254
HasValidators
different(mixed $data)
Enforce rule where response and $match parameter needs to be different.
in
HasValidators at line 269
void
displayErrorMessages()
Displays a list of all error messages.
in
HasValidators at line 285
HasValidators
dotNotation()
Ensures response is in dot notation format.
in
HasValidators at line 302
HasValidators
email()
Ensures input is a valid E-mail address.
in
HasValidators at line 317
HasValidators
fieldName(string|array $fieldName)
Sets name of field to be validated.
in
HasValidators at line 333
void
includeDeleted(bool|string $includeDeleted, array $queryParams)
Supports includeDeleted feature for database operations.
in
HasValidators at line 344
HasValidators
integer()
Enforce rule where input must be an integer.
in
HasValidators at line 358
HasValidators
ip()
Enforce rule where input must be a valid IP address.
in
HasValidators at line 376
HasValidators
isPortUsed(array $attributes)
Checks if a port on a particular host is in use. Assists in verifying if a port is available for a serve command. If the port is already in use an error message is presented to the user.
in
HasValidators at line 405
HasValidators
list(array $attributes)
Ensure user inputs valid comma separated list of values. The user must provide the following in the $attributes parameter: 1) Class containing full namespaced path 2) Name of function that returns an array of strings or a comma separated array of strings.
3) A string value in this array as an alias (optional).
in
HasValidators at line 443
HasValidators
lower()
Enforces rule when input must contain at least one lower case character.
in
HasValidators at line 458
HasValidators
match(mixed $match)
Enforce rule where response and $match parameter needs to match.
in
HasValidators at line 474
HasValidators
max(int|array $maxRule)
Ensures input meets requirements for maximum allowable length.
in
HasValidators at line 490
HasValidators
min(int|array $minRule)
Ensures input meets requirements for minimum allowable length.
in
HasValidators at line 505
HasValidators
negative()
Enforces rule when input must be a negative number.
in
HasValidators at line 519
HasValidators
noSpecialChars()
Enforces rule when input must contain no special characters.
in
HasValidators at line 533
HasValidators
notReservedKeyword()
Enforce rule when reserved keywords should be avoided.
in
HasValidators at line 547
HasValidators
notReservedSQLKeyword()
Enforce rule when reserved SQL keywords should be avoided.
in
HasValidators at line 561
HasValidators
number()
Enforces rule when input must contain at least one numeric character.
in
HasValidators at line 575
HasValidators
numeric()
Enforce rule where input must contain only numeric characters.
in
HasValidators at line 597
static protected void
parseAttributes(object $object, array $validators)
Parse array containing additional validators or attributes for FrameworkQuestion as strings along with any additional parameters that maybe expected.
in
HasValidators at line 618
HasValidators
required()
Ensures required input is entered.
in
HasValidators at line 631
HasValidators
positive()
Enforces rule when input must a positive number.
in
HasValidators at line 645
HasValidators
queue()
Validates if queue exists in database or redis.
in
HasValidators at line 670
HasValidators
setValidator(callable $validator)
Adds validator to array of validators to be used.
in
HasValidators at line 680
HasValidators
special()
Enforces rule when input must contain at least one special character.
in
HasValidators at line 694
HasValidators
tel()
Enforces rule where input must be a valid phone number.
in
HasValidators at line 718
HasValidators
testFilterNotation()
Ensures response is in colon notation format.
in
HasValidators at line 739
static protected array
tokens(string $data)
Split on commas (tolerate spaces), normalize to lowercase, drop empties.
Useful for cases where you have a comma separated string.
in
HasValidators at line 752
HasValidators
unique(array $attributes)
Checks if value already exists in a database.
in
HasValidators at line 796
HasValidators
upper()
Enforces rule when input must contain at least one lower case character.
in
HasValidators at line 810
HasValidators
url()
Enforce rule where input must be a valid URL.
in
HasValidators at line 826
protected bool
validate(mixed $response)
Calls validator callbacks. This function also ensures validators don't bleed into next question if instance is reused.
in
HasCasts at line 53
protected array
casts()
Returns the casts for this model. Override to declare casts with a method instead of the $casts property.
in
HasCasts at line 62
array
getCasts()
Returns all casts from the $casts property and the casts() method.
in
HasCasts at line 77
CarbonInterface|null
date(string $attribute)
Returns an attribute as a Carbon instance in the application timezone.
Works for any attribute holding a date, whether or not it is declared in $casts. Undeclared attributes are treated as datetime.
in
HasCasts at line 97
protected CarbonInterface|null
asDateTime(mixed $value, string $type = 'datetime')
Converts a raw value into a Carbon instance according to a cast type.
Datetime strings without a timezone are read as UTC. Plain Y-m-d strings are calendar dates and are never shifted between timezones.
in
HasCasts at line 126
protected string
serializeDate(CarbonInterface $date)
Formats a datetime for JSON. Override to change the wire format for every datetime cast on a model that has no explicit :format.
The default, ISO 8601 in UTC with a Z suffix, is parsed the same way by every browser and by Chappy's JavaScript datetime utilities.
in
HasCasts at line 135
array
toArray()
Returns the model's public properties with casts applied.
in
HasCasts at line 163
mixed
jsonSerialize()
Used by json_encode().
in
HasCasts at line 174
private array
parseCast(string $cast)
Splits "type:format" and validates the type.
in
HasCasts at line 194
private array
publicAttributes()
Returns only public properties, exactly what json_encode() exposed before this trait existed. Called from outside class scope so protected and private properties are excluded.
in
Model at line 66
__construct()
Default constructor.
in
Model at line 76
void
afterDelete()
Called before delete.
in
Model at line 83
void
afterSave()
Called before save.
in
Model at line 101
Model
assign(array $params, array $list = [], string $assignmentFilter = self::BLACKLIST)
Update the object with an associative array.
Field filtering, in priority order:
- An explicit $list passed by the caller (with $assignmentFilter) always wins.
- Otherwise, if the model declares a whiteList constant, only those fields are assignable (fail-closed — new columns are rejected by default).
- Otherwise, if the model declares a blackList constant, those fields are rejected and everything else is assignable (fail-open).
- Otherwise, no field filtering (only property_exists still applies).
in
Model at line 134
void
beforeDelete()
This runs before delete, needs to return a boolean
at line 222
void
beforeSave()
Implements beforeSave function described in Model parent class.
Ensures password is not in plain text but a hashed one. The reset_password flag is also set to 0.
in
Model at line 149
static int
count()
Retrieves number of rows affected or returned by the last query. This is a wrapper function for the DB::count function.
in
Model at line 179
bool
delete()
Wrapper for database delete function. If not softDelete we set it.
If row is set to softDelete we call the database delete function.
in
Model at line 201
static array
getColumns()
Gets columns from table.
in
Model at line 211
array
getColumnsForSave()
Gets an associative array of field values for insert or updating.
in
Model at line 253
array
getErrorMessages()
Displays error messages when form validation fails.
in
Model at line 263
static protected array
_fetchStyleParams(array $params)
Used to set default fetchStyle param.
in
Model at line 277
static array|bool
find(array $params = [])
Wrapper for the find function that is found in the DB class.
in
Model at line 293
static array
findAllByUserId(int $user_id, array $params = [])
Retrieves list of all records within a table related to a user.
in
Model at line 310
static object|bool
findById(int $id)
Get result from database by primary key ID.
in
Model at line 326
static array|bool
findByTable(string $table, array $params = [])
Performs a database query against a specified table using the same query-building logic as the default find method.
This method is useful when querying a different table than the one defined by the model's static::$_table property (e.g., joining or selecting from related tables).
in
Model at line 342
static object|bool
findFirst(array $params = [])
Wrapper for the findFirst function that is found in the DB class.
in
Model at line 357
static int
findTotal(array $params = [])
Returns number of records in a table. A wrapper function for findTotal function in DB class.
in
Model at line 372
bool
insert(array $fields)
Wrapper for database insert function.
in
Model at line 384
bool
isNew()
Checks if an object is a new insertion or an existing record.
in
Model at line 417
void
onConstruct()
Runs when the object is constructed.
in
Model at line 425
protected void
populateObjData(array|object $result)
Populates object with data.
in
Model at line 462
void
runValidation(bool|string $param, array $validators = [], string|null $fieldName = null)
Checks if results of validation is true or false. If false, the $this->_validates boolean instance variable is set to false. There are two ways to provide parameters for validation. You can pass the results from chaining functions and use just one parameter. Or you can provide the value of the field's name attribute, an array of validators, and a value for how you want the name of the field represented in error messages. If this value is not provided then the name attribute is used in messaging.
in
Model at line 485
bool
save()
Wrapper for update and insert functions. A failed form validation will cause this function to return false.
in
Model at line 526
static protected array
_softDeleteParams(array $params)
Adds to the conditions to avoid getting soft deleted rows returned
in
Model at line 568
static array
toOptions(string $valueField, string $labelField, array $conditions = [])
Projects model rows into a [value => label] options map for form controls.
This is the standard source for controls whose options are value/label pairs: select, radio groups, checkbox groups, and datalists in list (non-range) mode. Each row contributes one entry: $row->$valueField => $row->$labelField.
NOT for range inputs. A range's min/max/step are numeric params, not a map, and its datalist tick pairs are almost always developer-set literals rather than model rows — so build those inline. Only use toOptions for a range if its tick values are genuinely data-driven, which is rare.
The value field should be whatever gets stored/submitted (and matched against on populate); the label field is the display text. For ACLs, both are the name: toOptions('acl', 'acl'). For a typical lookup: toOptions('id', 'name').
in
Model at line 591
bool
update(array $fields)
Wrapper for the update function found in the DB class.
in
Model at line 621
static int
updateWhere(array $fields, array $params)
Updates one or more rows in this model's underlying table using your framework's params-style conditions.
This method delegates to the DB::updateWhere() method and allows
you to pass both the fields to update and a parameterized WHERE
clause (using conditions and bind arrays just like find/findFirst).
Example:
Queue::updateWhere(
['reserved_at' => date('Y-m-d H:i:s')],
['conditions' => 'id = ?', 'bind' => [$jobId]]
);
in
Model at line 631
bool
validationPassed()
Getter function for the $_validates boolean instance variable.
at line 269
void
validator()
Performs validation on user related forms.
in
HasTimestamps at line 28
void
timeStamps()
Sets values for timestamp fields.
in
IsPrincipal at line 54
mixed
getAuthIdentifier()
Gets the value of the primary identifier.
in
IsPrincipal at line 63
string
getAuthIdentifierName()
Gets the name of the primary identifier column.
in
IsPrincipal at line 72
string|null
getAuthPassword()
Gets the hashed password for this user.
in
IsPrincipal at line 81
string
getAuthPasswordName()
Gets the name of the password column.
in
IsPrincipal at line 90
string|null
getRememberToken()
Gets the current remember-me token.
at line 262
string|null
getRememberTokenName()
Remember-me tokens are stored per device in the user_sessions table, not on the users row.
in
IsPrincipal at line 112
void
setRememberToken(string $value)
Sets token value to persist.
in
PasswordPolicy at line 22
bool
isMaxLength()
Gets max length rule for password.
in
PasswordPolicy at line 31
bool
isMinLength()
Gets minimum rule for password.
in
PasswordPolicy at line 40
bool
lowerChar()
Gets lower case character rule for password.
in
PasswordPolicy at line 49
int
maxLength()
Gets max length for password.
in
PasswordPolicy at line 58
int
minLength()
Gets minimum length for password.
in
PasswordPolicy at line 67
bool
numericChar()
Gets numeric character rule for password.
in
PasswordPolicy at line 76
bool
specialChar()
Gets special character rule for password.
in
PasswordPolicy at line 85
bool
upperChar()
Gets upper case character rule for password.
in
PasswordPolicy at line 96
static private bool
policyFlag(string $configKey, string $envKey)
Reads a boolean password setting.
in
PasswordPolicy at line 109
static private int
policyLength(string $configKey, string $envKey, int $default)
Reads a numeric password setting.
at line 144
array
getAcls()
Returns the user's assigned ACLs as an array.
Decodes the JSON-encoded acl field. Returns an empty array if the field is null, empty, or not valid JSON — so callers always get an array.
at line 155
bool
isInactiveChecked()
Assists in setting value of inactive field based on POST.
at line 166
bool
isResetPWChecked()
Assists in setting value of reset_password field based on POST.
at line 176
bool
hasAcl(string $acl)
Checks if the user has a specific ACL assigned.
at line 191
void
setChangePassword(bool $value)
Setter function for $changePassword.
at line 200
protected void
userBeforeSave()
To be called within beforeSave().
at line 235
static array|bool
findAllUsersExceptCurrent(int $current_user_id, array $params = [])
Retrieves a list of all users except current logged in user.
at line 252
static bool|object
findByUserName(string $username)
Finds user by username in the users table.