Skip to main content

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 the Lyger\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:
Only attributes listed in $fillable can be set via create() or fill() methods. This protects against mass-assignment vulnerabilities.

Hidden Attributes

Hide attributes when converting to array or JSON:

Timestamps

When enabled, Eloquent automatically manages created_at and updated_at columns.

Attribute Casting

Cast attributes to specific types:
Supported casts: 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 a Collection 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