Overview
TheModel class provides an Eloquent-style ORM interface for interacting with database tables. It supports relationships, query building, mass assignment protection, attribute casting, and timestamps.
Class Reference
Lyger\Database\Model
Base class for all Eloquent models, inspired by Laravel Eloquent. Location:Lyger/Database/Model.php
Properties
string
The database table associated with the model. If not set, defaults to the pluralized, snake_case class name.
string
default:"'id'"
The primary key for the model.
array
default:"[]"
The attributes that are mass assignable.
The attributes that should be hidden for serialization.
array
default:"[]"
The attributes that should be cast to native types.
array
default:"['created_at', 'updated_at', 'deleted_at']"
The attributes that should be mutated to dates.
bool
default:"true"
Indicates if the model should be timestamped.
Methods
Constructor
array
default:"[]"
Initial attributes for the model
Query Methods
query()
QueryBuilder instance
Example:
find()
mixed
The primary key value
null if not found
Example:
findOrFail()
mixed
The primary key value
\RuntimeException if model not found
Example:
all()
Collection of model instances
Example:
create()
array
The attributes for the new model
Instance Methods
fill()
$fillable attributes.
array
Attributes to fill
$this for method chaining
Example:
save()
true on success, false on failure
Example:
delete()
true if deleted, false otherwise
Example:
toArray()
$hidden attributes and applying casts.
Returns: Array representation of the model
Example:
toJson()
int
default:"0"
JSON encoding options
getKey()
null
Example:
Relationship Methods
hasOne()
The related model class name
string
The foreign key name (defaults to
{model}_id)HasOne relationship instance
Example:
hasMany()
The related model class name
string
The foreign key name (defaults to
{model}_id)HasMany relationship instance
Example:
belongsTo()
The related model class name
string
The foreign key name
BelongsTo relationship instance
Example:
belongsToMany()
The related model class name
string
The pivot table name (defaults to alphabetically sorted model names)
BelongsToMany relationship instance
Example:
Usage Examples
Basic Model Definition
Attribute Casting
Magic Methods
The Model class supports magic property access:Timestamps
Models automatically managecreated_at and updated_at timestamps:
To disable timestamps, set
protected bool $timestamps = false in your model.Best Practices
- Always define
$fillableto protect against mass assignment vulnerabilities - Use
$hiddento exclude sensitive attributes from JSON/array conversion - Define relationships in dedicated methods for better organization
- Use attribute casting for type safety
Related
- QueryBuilder - Fluent query builder interface
- Schema - Database schema builder
- Migration - Database migration system