Skip to main content

Overview

The Model 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

$table
string
The database table associated with the model. If not set, defaults to the pluralized, snake_case class name.
$primaryKey
string
default:"'id'"
The primary key for the model.
$fillable
array
default:"[]"
The attributes that are mass assignable.
$hidden
array
default:"[]"
The attributes that should be hidden for serialization.
$casts
array
default:"[]"
The attributes that should be cast to native types.
$dates
array
default:"['created_at', 'updated_at', 'deleted_at']"
The attributes that should be mutated to dates.
$timestamps
bool
default:"true"
Indicates if the model should be timestamped.

Methods

Constructor

public function __construct(array $attributes = [])
Create a new model instance with optional attributes.
attributes
array
default:"[]"
Initial attributes for the model
Example:
$user = new User([
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);

Query Methods

query()

public static function query(): QueryBuilder
Get a new query builder instance for the model. Returns: QueryBuilder instance Example:
$users = User::query()
    ->where('active', '=', 1)
    ->orderBy('created_at', 'DESC')
    ->get();

find()

public static function find($id): ?static
Find a model by its primary key.
id
mixed
The primary key value
Returns: Model instance or null if not found Example:
$user = User::find(1);
if ($user) {
    echo $user->name;
}

findOrFail()

public static function findOrFail($id): static
Find a model by its primary key or throw an exception.
id
mixed
The primary key value
Returns: Model instance Throws: \RuntimeException if model not found Example:
try {
    $user = User::findOrFail(999);
} catch (\RuntimeException $e) {
    echo "User not found!";
}

all()

public static function all(): Collection
Get all records from the database. Returns: Collection of model instances Example:
$users = User::all();
foreach ($users as $user) {
    echo $user->name;
}

create()

public static function create(array $attributes): static
Create and save a new model instance.
attributes
array
The attributes for the new model
Returns: Created model instance Example:
$user = User::create([
    'name' => 'Jane Doe',
    'email' => 'jane@example.com'
]);

Instance Methods

fill()

public function fill(array $attributes): self
Fill the model with an array of attributes. Only fills $fillable attributes.
attributes
array
Attributes to fill
Returns: $this for method chaining Example:
$user = new User();
$user->fill([
    'name' => 'John',
    'email' => 'john@example.com'
]);

save()

public function save(): bool
Save the model to the database. Performs an update if the model exists, otherwise inserts a new record. Returns: true on success, false on failure Example:
$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();

// Or update existing
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

delete()

public function delete(): bool
Delete the model from the database. Returns: true if deleted, false otherwise Example:
$user = User::find(1);
$user->delete();

toArray()

public function toArray(): array
Convert the model to an array, respecting $hidden attributes and applying casts. Returns: Array representation of the model Example:
$user = User::find(1);
$data = $user->toArray();
// ['id' => 1, 'name' => 'John', 'email' => 'john@example.com']

toJson()

public function toJson(int $options = 0): string
Convert the model to JSON.
options
int
default:"0"
JSON encoding options
Returns: JSON string Example:
$user = User::find(1);
echo $user->toJson(JSON_PRETTY_PRINT);

getKey()

public function getKey(): mixed
Get the primary key value for the model. Returns: Primary key value or null Example:
$user = User::find(1);
echo $user->getKey(); // 1

Relationship Methods

hasOne()

public function hasOne(string $related, string $foreignKey = null): HasOne
Define a one-to-one relationship.
The related model class name
foreignKey
string
The foreign key name (defaults to {model}_id)
Returns: HasOne relationship instance Example:
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

$user = User::find(1);
$profile = $user->profile();

hasMany()

public function hasMany(string $related, string $foreignKey = null): HasMany
Define a one-to-many relationship.
The related model class name
foreignKey
string
The foreign key name (defaults to {model}_id)
Returns: HasMany relationship instance Example:
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

$user = User::find(1);
$posts = $user->posts();

belongsTo()

public function belongsTo(string $related, string $foreignKey = null): BelongsTo
Define an inverse one-to-one or one-to-many relationship.
The related model class name
foreignKey
string
The foreign key name
Returns: BelongsTo relationship instance Example:
class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

$post = Post::find(1);
$user = $post->user();

belongsToMany()

public function belongsToMany(string $related, string $pivotTable = null): BelongsToMany
Define a many-to-many relationship.
The related model class name
pivotTable
string
The pivot table name (defaults to alphabetically sorted model names)
Returns: BelongsToMany relationship instance Example:
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

$user = User::find(1);
$roles = $user->roles();

Usage Examples

Basic Model Definition

namespace App\Models;

use Lyger\Database\Model;

class User extends Model
{
    protected string $table = 'users';
    
    protected array $fillable = [
        'name',
        'email',
        'password'
    ];
    
    protected array $hidden = [
        'password'
    ];
    
    protected array $casts = [
        'email_verified' => 'bool',
        'created_at' => 'datetime'
    ];
}

Attribute Casting

class Product extends Model
{
    protected array $casts = [
        'price' => 'float',
        'in_stock' => 'bool',
        'metadata' => 'array',
        'tags' => 'json'
    ];
}

$product = Product::find(1);
$price = $product->price; // Automatically cast to float
$inStock = $product->in_stock; // Automatically cast to boolean

Magic Methods

The Model class supports magic property access:
$user = User::find(1);

// Get attribute
echo $user->name;

// Set attribute
$user->name = 'John Doe';

// Check if attribute exists
if (isset($user->email)) {
    echo $user->email;
}

// Unset attribute
unset($user->temporary_field);

Timestamps

Models automatically manage created_at and updated_at timestamps:
$user = new User();
$user->name = 'John';
$user->save();
// created_at and updated_at are automatically set

$user->name = 'Jane';
$user->save();
// updated_at is automatically updated
To disable timestamps, set protected bool $timestamps = false in your model.

Best Practices

  • Always define $fillable to protect against mass assignment vulnerabilities
  • Use $hidden to exclude sensitive attributes from JSON/array conversion
  • Define relationships in dedicated methods for better organization
  • Use attribute casting for type safety