Introduction
Eloquent is Lyger’s implementation of the Active Record pattern, providing an elegant and expressive way to interact with your database. Each database table has a corresponding Model class that is used to interact with that table.Defining Models
Basic Model Definition
Create a model by extending theLyger\Database\Model class:
app/Models/User.php
If you don’t specify a
$table property, Eloquent will automatically use the lowercase, pluralized class name (e.g., User becomes users).Model Properties
Table Name
Primary Key
Fillable Attributes
Define which attributes can be mass-assigned:Hidden Attributes
Hide attributes when converting to array or JSON:Timestamps
created_at and updated_at columns.
Attribute Casting
Cast attributes to specific types:int, integer, float, double, bool, boolean, string, array, json, datetime, date
Retrieving Models
Find by Primary Key
Retrieving All Records
Using Query Builder Methods
All Query Builder methods are available on models:Creating Models
Using Create Method
Using Save Method
Using Fill Method
The
create() and fill() methods only work with attributes listed in the $fillable property.Updating Models
Update Using Save
Mass Update via Query
Deleting Models
Delete Single Model
Delete via Query
Accessing Attributes
Magic Properties
Array Access
Serialization
To Array
To JSON
Collections
Eloquent returns aCollection instance for multi-record results:
Model Methods
Getting the Primary Key
Getting the Table Name
Complete Example
Here’s a comprehensive example demonstrating Eloquent usage:app/Models/Post.php
Best Practices
1
Use Mass Assignment Protection
Always define
$fillable to protect against mass-assignment vulnerabilities:2
Hide Sensitive Data
Use
$hidden to exclude sensitive attributes from arrays and JSON:3
Use Type Casting
Cast attributes to appropriate types for better type safety:
4
Enable Timestamps
Let Eloquent manage timestamps automatically:
Next Steps
Relationships
Define relationships between your models
Query Builder
Learn more about the underlying Query Builder