Skip to main content

Models

A model maps one table to a class: rows become objects, columns become properties.

php omnitrix make:model Product --migration
<?php

declare(strict_types=1);

namespace App\Models;

use DateTimeImmutable;
use Omnitrix\Database\Model;

/**
* @property int $id
* @property string $name
* @property float $price
* @property bool $active
* @property array<string, mixed> $attributes_json
* @property DateTimeImmutable|null $created_at
* @property DateTimeImmutable|null $updated_at
*/
final class Product extends Model
{
protected static array $fillable = ['name', 'price', 'active', 'attributes_json'];

protected static array $hidden = ['cost_price'];

protected static array $casts = [
'price' => 'float',
'active' => 'bool',
'attributes_json' => 'array',
];
}

The @property lines are optional; they let your IDE and static analysis know the attribute types.

Conventions and settings​

PropertyDefaultMeaning
$tableplural snake case of the class (OrderItem → order_items)table name
$primaryKeyidprimary key column
$incrementingtruethe key is generated by the database
$timestampstruemaintain created_at and updated_at
$connectionnull (default connection)connection name from config/database.php
$fillable[]attributes accepted by create(), fill() and update()
$hidden[]attributes left out of JSON and toArray()
$casts[]attribute types (see below)

Retrieving​

$product = Product::find(1); // or null
$product = Product::findOrFail(1); // or a 404 response
$all = Product::all();

$cheap = Product::where('active', true)
->where('price', '<', 10)
->orderBy('price')
->limit(20)
->get(); // Collection<Product>

$first = Product::query()->latest()->first();
$count = Product::where('active', true)->count();
$names = Product::query()->pluck('name');
$page = Product::query()->orderBy('id')->paginate(perPage: 20, page: 2);

Every method of the query builder is available on Model::query() (whereIn, whereNull, whereBetween, join, groupBy, lockForUpdate, aggregates, …). Queries that return rows return models.

Creating, updating, deleting​

$product = Product::create(['name' => 'Lamp', 'price' => 19.9]);

$product->price = 17.5;
$product->save(); // updates only changed columns

$product->update(['name' => 'Desk lamp']); // fill() + save()

$product->delete();

Product::where('active', false)->update(['archived' => 1]); // many rows, no models loaded
Product::where('created_at', '<', '2020-01-01')->delete();

create(), fill() and update() only accept attributes listed in $fillable; other keys are ignored. Use forceFill() to set guarded attributes from trusted code.

Casts​

CastRead asStored as
int / integerintinteger
float / double / decimalfloatnumber
bool / booleanbool1 / 0
stringstringstring
array / jsondecoded arrayJSON text
datetimeDateTimeImmutableY-m-d H:i:s
dateDateTimeImmutableY-m-d

created_at and updated_at are cast to DateTimeImmutable automatically. In JSON, dates are written in ISO 8601.

JSON responses​

Return a model, a collection or a paginator from a route handler and it becomes JSON:

$router->get('/products/{id:\d+}', fn (Request $r) => Product::findOrFail($r->routeInt('id')));
$router->get('/products', fn (Request $r) => Product::query()->paginate(20, (int) ($r->queryParam('page') ?? 1)));

A paginator produces {"data": [...], "meta": {"total", "per_page", "current_page", "last_page"}}. Loaded relationships are included; $hidden attributes are not.

Collections​

get(), all() and many-relationships return an Omnitrix\Database\Collection: iterable, countable and JSON-serialisable, with first(), last(), isEmpty(), map(), filter(), each(), pluck(), keyBy(), modelKeys(), toArray() and load().

Models and concurrency​

Models are plain objects with no connection of their own, so they are safe in coroutines. Queries run on pooled connections; independent queries can run in parallel:

$results = Async::all([
'products' => fn () => Product::where('active', true)->count(),
'orders' => fn () => Order::where('status', 'paid')->count(),
]);

Do not share one model instance between coroutines that modify it at the same time.