Models
The Models class provides an active record pattern for database operations, including CRUD functionality with protection against mass assignment vulnerabilities.Namespace
Protected Properties
Methods
create()
Inserts a new record into the database table.Associative array of field names and values to insert. Only fields listed in
$fillables will be inserted.Returns the result from the database query execution
Behavior
- Filters the request data to only include fields defined in
$fillables(protection against mass assignment) - Throws an exception if no valid fields are provided
- Builds a parameterized INSERT query
- Executes the query using prepared statements
Example
update()
Updates an existing record in the database table.Associative array of field names and values to update. Only fields listed in
$fillables will be updated.The ID of the record to update
This method does not return a value
Behavior
- Filters the request data to only include fields defined in
$fillables - Throws an exception if no valid fields are provided
- Builds a parameterized UPDATE query with WHERE id clause
- Executes the query using prepared statements
Example
delete()
Deletes a record from the database table by ID.The ID of the record to delete
This method does not return a value
Behavior
- Throws an exception if no ID is provided
- Executes a DELETE query with WHERE id clause
- Uses prepared statements for security
Example
select()
Performs a SELECT query with flexible filtering, ordering, and limiting options.Array of column names to select (e.g.,
['id', 'name', 'email'])Associative array of column-value pairs for WHERE conditions. Multiple conditions are combined with AND.
ORDER BY clause (e.g.,
'created_at DESC', 'name ASC')Maximum number of records to return. Use
0 for no limit.Returns an array of associative arrays containing the query results
Behavior
- Throws an exception if columns array is empty
- Builds a SELECT query with optional WHERE, ORDER BY, and LIMIT clauses
- All WHERE conditions are combined with AND logic
- Uses prepared statements to prevent SQL injection
Example
findByID()
Finds and returns a single record by its ID.The ID of the record to retrieve
Returns an associative array containing the record data (first result only)
Behavior
- Throws an exception if no ID is provided
- Executes a SELECT query with WHERE id clause
- Returns only the first matching record
- Note: Does not use prepared statements (consider using
select()for safer queries)
Example
Usage Pattern
Extend the Models class and define the table and fillable fields:Mass Assignment Protection
The$fillables array protects against mass assignment vulnerabilities by only allowing specified fields to be inserted or updated: