Repository navigation
Eloquent Database ORM
The Machinjiri ORM is a lightweight ActiveRecord-style ORM built for the Machinjiri PHP framework. It provides an intuitive, expressive API for interacting with your database — inspired by Laravel's Eloquent but designed to be dependency-light and easy to understand.
| Feature | Description |
|---|---|
| ActiveRecord Models | Class-based models with attributes, casting, and lifecycle events |
| Fluent Query Builder | Chainable select, where, join, orderBy, limit API |
| Attribute Casting | Auto-cast to int, float, bool, array, json, datetime
|
| DateTimeHandler | Timezone-aware date/time handling with rich helper methods |
| Soft Deletes | Mark records as deleted without physically removing them |
| Query Caching | Cache expensive queries with tags and TTL |
| Model Events | Hook into creating, created, saving, saved, deleting, deleted
|
| Schema Builder | Create and alter tables with a Blueprint-style DSL |
| Aggregates |
count, sum, avg, min, max built-in |
| Auto Timestamps | Automatically manages created_at and updated_at
|
| CLI Generators | Scaffold controllers, models, and middleware via Artisan commands |
┌─────────────────────────────────────────────────────────────┐
│ Your Application │
└───────────────────────────┬─────────────────────────────────┘
│
┌─────────────▼─────────────┐
│ AbstractModel │ ← Your models extend this
│ (CRUD, casting, events) │
└─────────────┬─────────────┘
│
┌─────────────▼─────────────┐
│ QueryBuilder │ ← Fluent SQL builder
└─────────────┬─────────────┘
│
┌─────────────▼─────────────┐
│ DatabaseConnection │ ← PDO wrapper
│ + Grammar │ ← SQL dialect
└───────────────────────────┘
Since Machinjiri is framework-internal, the ORM ships with the core. To use it:
use Mlangeni\Machinjiri\Core\Artisans\Base\AbstractModel;
use Mlangeni\Machinjiri\Core\Database\Builders\QueryBuilder;
use Mlangeni\Machinjiri\Core\Database\DatabaseConnection;Ensure your DatabaseConnection is configured (host, database, credentials). All models and queries resolve the active connection automatically.
php artisan make:model UserThis generates app/Models/User.php:
<?php
namespace App\Models;
use Mlangeni\Machinjiri\Core\Artisans\Base\AbstractModel;
class User extends AbstractModel
{
protected string $table = 'users';
protected array $fillable = ['name', 'email', 'password'];
protected array $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'is_active' => 'boolean',
];
}use App\Models\User;
$user = User::create([
'name' => 'Alice',
'email' => 'alice@example.com',
]);// Find by primary key
$user = User::find(1);
// Fluent queries
$users = User::where('is_active', '=', true)
->orderBy('name', 'ASC')
->limit(10)
->get();
// First match
$user = User::where('email', '=', 'alice@example.com')->first();$user->name = 'Alice Smith';
$user->save();
$user->delete();| Property | Type | Default | Purpose |
|---|---|---|---|
$table |
string |
snake_case plural | Database table name |
$primaryKey |
string |
'id' |
Primary key column |
$keyType |
string |
'int' |
Primary key type |
$incrementing |
bool |
true |
Auto-incrementing PK |
$fillable |
array |
[] |
Mass-assignable columns |
$guarded |
array |
['*'] |
Blocked columns (default: all blocked) |
$casts |
array |
[] |
Attribute type conversions |
$timestamps |
bool |
true |
Auto-manage timestamps |
$dateFormat |
string |
'Y-m-d H:i:s' |
DB date storage format |
$timezone |
string |
'UTC' |
Model timezone |
$softDelete |
bool |
false |
Enable soft deletes |
$cacheEnabled |
bool |
false |
Enable query caching |
$cacheTtl |
?int |
null |
Cache TTL (seconds) |
$cacheTags |
array |
[] |
Cache tags |
Machinjiri blocks all mass assignment by default ($guarded = ['*']). You must explicitly opt-in:
protected array $fillable = ['name', 'email'];Or use forceFill() to bypass:
$user->forceFill(['name' => 'Alice', 'role' => 'admin']);class Post extends AbstractModel
{
protected string $table = 'posts';
protected string $primaryKey = 'post_id';
protected bool $incrementing = false;
protected string $keyType = 'string';
protected array $fillable = ['title', 'body', 'author_id'];
protected array $casts = [
'published_at' => 'datetime',
'metadata' => 'array',
];
}$post = Post::find(1);
echo $post->title; // __get → getAttribute()
$post->title = 'New Title'; // __set → setAttribute()
isset($post->title); // __isset
unset($post->title); // __unset$post->toArray(); // Casted attributes as array
$post->toJson(); // JSON stringThe QueryBuilder is the engine behind every model query. You can also use it standalone.
use Mlangeni\Machinjiri\Core\Database\Builders\QueryBuilder;
$builder = QueryBuilder::builder('users');
$rows = $builder->select(['id', 'name'])->get();QueryBuilder::builder('users')
->select(['id', 'name', 'email'])
->distinct()
->get();// Basic
->where('age', '>', 18)
// Multiple conditions (AND)
->where('age', '>', 18)
->where('country', '=', 'Zimbabwe')
// OR conditions
->where('role', '=', 'admin')
->orWhere('role', '=', 'moderator')
// IN
->whereIn('id', [1, 2, 3])
// IS NULL
->whereNull('deleted_at')
// Nested (grouped) conditions
->where(function ($q) {
$q->where('status', '=', 'active')
->orWhere('status', '=', 'pending');
})Generated SQL:
SELECT * FROM `users`
WHERE age > ?
AND country = ?
AND role = ? OR role = ?
AND id IN (?, ?, ?)
AND deleted_at IS NULL
AND (status = ? OR status = ?)QueryBuilder::builder('users')
->join('posts', 'users.id', '=', 'posts.user_id')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->select(['users.name', 'posts.title'])
->get();->orderBy('created_at', 'DESC')
->orderBy('name', 'ASC')
->limit(20)
->offset(40)QueryBuilder::builder('orders')
->select(['user_id', 'COUNT(*) as total'])
->groupBy('user_id')
->get();// Via model
$user = User::create(['name' => 'Alice', 'email' => 'alice@example.com']);
// Via new instance
$user = new User();
$user->name = 'Bob';
$user->email = 'bob@example.com';
$user->save();
// Via query builder
QueryBuilder::builder('users')->insert([
'name' => 'Charlie',
'email' => 'charlie@example.com',
])->execute();User::find(1); // Find by PK
User::all(); // All records
User::where('role', 'admin')->get();
User::where('email', 'a@b.com')->first();$user = User::find(1);
$user->name = 'Updated Name';
$user->save();
// Or bulk via builder
QueryBuilder::builder('users')
->where('role', 'guest')
->update(['is_active' => true])
->execute();$user = User::find(1);
$user->delete();
// Or builder
QueryBuilder::builder('users')
->where('id', '=', 5)
->delete()
->execute();// Find or create with attributes
$user = User::firstOrCreate(
['email' => 'alice@example.com'],
['name' => 'Alice']
);
// Find and update, or create
$user = User::updateOrCreate(
['email' => 'alice@example.com'],
['name' => 'Alice Smith', 'role' => 'admin']
);Casting converts DB values into PHP types automatically.
| Cast | DB Storage | PHP Type |
|---|---|---|
int, integer
|
INT |
int |
float, double
|
FLOAT/DECIMAL
|
float |
string |
VARCHAR |
string |
bool, boolean
|
TINYINT(1) |
bool |
array, json
|
TEXT |
array |
object |
TEXT |
stdClass |
datetime, date, timestamp
|
DATETIME |
DateTimeHandler |
class Product extends AbstractModel
{
protected array $casts = [
'price' => 'float',
'in_stock' => 'boolean',
'metadata' => 'array',
'published_at'=> 'datetime',
];
}
$product = Product::find(1);
var_dump($product->in_stock); // bool(true)
var_dump($product->metadata); // array(...)
echo $product->published_at->format('Y-m-d'); // "2024-01-15"Machinjiri ships with DateTimeHandler — a timezone-aware, immutable-by-convention date wrapper. DateTime-cast attributes are automatically converted.
use Mlangeni\Machinjiri\Core\Date\DateTimeHandler;
$now = new DateTimeHandler('now', 'Africa/Harare');
$date = new DateTimeHandler('2024-03-15', 'UTC');
$ts = DateTimeHandler::fromTimestamp(1710460800, 'UTC');$date->format('Y-m-d'); // "2024-03-15"
$date->getTimestamp(); // Unix timestamp
$date->addDays(7);
$date->subMonths(1);
$date->isPast();
$date->isFuture();
$date->diffInDays($other);$user = User::find(1);
// Returns a DateTimeHandler
echo $user->created_at->format('M d, Y');
// Assigning accepts strings, timestamps, or DateTimeHandler
$user->created_at = new DateTimeHandler('2024-01-01');
$user->updated_at = '2024-01-01 12:00:00';
$user->save();Soft deletes mark records as deleted without physically removing them.
class Post extends AbstractModel
{
protected bool $softDelete = true;
}
⚠️ Yourpoststable must have adeleted_atnullable column.
// Soft delete
$post->delete();
// Restore
$post->restore();
// Check trashed
$post->trashed(); // bool
// Queries automatically exclude trashed records
Post::all(); // Only non-deleted
// Include trashed
Post::withTrashed()->get();
// Only trashed
Post::onlyTrashed()->get();
// Force permanent delete
$post->forceDelete();Hook into the model lifecycle:
// Available events
// booting, saving, saved, created, updated, deleting, deleteduse Mlangeni\Machinjiri\Core\Artisans\Events\EventListener;
$events = resolve(EventListener::class);
$events->listen('model.saving.App\Models\User', function ($user) {
if (empty($user->name)) {
throw new \Exception('Name is required');
}
});
$events->listen('model.created.App\Models\User', function ($user) {
// Send welcome email
});
$events->listen('model.deleting.App\Models\User', function ($user) {
// Return false to cancel the delete
});Returning false from saving, deleting cancels the operation.
$events->listen('model.deleting.App\Models\Post', function ($post) {
if ($post->is_published) {
return false; // Prevent deletion
}
});Speed up read-heavy workloads with optional query caching.
class Article extends AbstractModel
{
protected static bool $cacheEnabled = true;
protected static ?int $cacheTtl = 300; // 5 minutes
protected static array $cacheTags = ['articles'];
}// Automatically cached
$articles = Article::where('published', '=', true)->get();
// Explicit cache management
Article::cached()->where('views', '>', 1000)->get();Cache is automatically invalidated on save, update, and delete.
$cache = resolve(CacheManager::class);
$cache->tags(['model.articles'])->clear(); // Manual clearBy default, created_at and updated_at are managed automatically.
protected bool $timestamps = false;protected const CREATED_AT = 'date_created';
protected const UPDATED_AT = 'date_modified';$post->touch(); // Update `updated_at` onlyCreate and alter tables programmatically.
use Mlangeni\Machinjiri\Core\Database\Builders\QueryBuilder;
$builder = QueryBuilder::builder();
$builder->createTableWithBlueprint('users', function ($table) {
$table->id();
$table->string('name', 100);
$table->string('email')->unique();
$table->boolean('is_active');
$table->decimal('balance', 10, 2);
$table->dateTime('last_login');
$table->foreignId('role_id');
$table->timestamps();
});$builder->alterTableWithBlueprint('users', function ($table) {
$table->addColumn('nickname', 'VARCHAR(50)');
$table->dropColumn('legacy_field');
$table->renameColumn('old_name', 'new_name');
$table->addIndex('idx_email', ['email']);
});$builder->dropTable('users')->execute();| Method | DB Type |
|---|---|
id() |
INT PRIMARY KEY AUTO_INCREMENT |
string($col, $len) |
VARCHAR($len) |
text($col) |
TEXT |
integer($col) |
INT |
boolean($col) |
TINYINT(1) |
float($col, $p, $s) |
FLOAT($p,$s) |
decimal($col, $p, $s) |
DECIMAL($p,$s) |
date($col) |
DATE |
dateTime($col) |
DATETIME |
timestamp($col) |
TIMESTAMP |
foreignId($col) |
INT UNSIGNED |
User::where('is_active', '=', true)->count();
User::where('is_active', '=', true)->count('email', true); // distinct
Order::sum('total');
Order::avg('total');
Order::min('total');
Order::max('total');Order::whereCurrentWeek('created_at')->sum('total');
Order::whereCurrentMonth('created_at')->get();
Order::whereCurrentYear('created_at')->get();
// Custom range
Order::whereDateRange('created_at', '2024-01-01', '2024-03-31')->get();QueryBuilder::builder('orders')
->select(['user_id', 'SUM(total) as revenue'])
->groupBy('user_id')
->orderBy('revenue', 'DESC')
->limit(10)
->get();The framework ships with Artisan commands to scaffold classes.
| Command | Description |
|---|---|
make:model <Name> |
Creates app/Models/<Name>.php
|
make:controller <Name> |
Creates app/Controllers/<Name>.php
|
make:middleware <Name> |
Creates app/Middleware/<Name>.php
|
get:env |
Dumps .env variables |
php artisan make:model InvoiceGenerates a fully-documented model with $fillable, $casts, $timestamps, and $softDelete stubs pre-configured.
$data = [
['name' => 'A', 'email' => 'a@x.com'],
['name' => 'B', 'email' => 'b@x.com'],
];
foreach ($data as $row) {
QueryBuilder::builder('users')->insert($row)->execute();
}Wrap your execute() calls in DatabaseConnection transactions:
$db = DatabaseConnection::getInstance();
try {
$db->beginTransaction();
$user = User::create(['name' => 'Alice']);
$profile = Profile::create(['user_id' => $user->id]);
$db->commit();
} catch (\Throwable $e) {
$db->rollBack();
throw $e;
}$offset = 0;
do {
$batch = User::query()->limit(500)->offset($offset)->get();
foreach ($batch as $row) {
// process...
}
$offset += 500;
} while (count($batch) === 500);class UserRepository
{
public function activeAdmins(): array
{
return User::where('is_active', '=', true)
->where('role', '=', 'admin')
->orderBy('name')
->get();
}
}abstract class TenantModel extends AbstractModel
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->table = 'tenant_' . $this->table;
}
}| Method | Returns | Description |
|---|---|---|
query() |
QueryBuilder |
New query builder |
cached() |
CachedQueryBuilder |
New cached builder |
find($id) |
?static |
Find by PK |
all() |
static[] |
All records |
create(array) |
static |
Create and save |
firstOrCreate($attrs, $vals) |
static |
Find or create |
firstOrNew($attrs, $vals) |
static |
Find or instantiate |
updateOrCreate($attrs, $vals) |
static |
Update or create |
withTrashed() |
QueryBuilder |
Include soft-deleted |
onlyTrashed() |
QueryBuilder |
Only soft-deleted |
| Method | Returns | Description |
|---|---|---|
save() |
bool |
Persist changes |
delete() |
bool |
Delete (soft or hard) |
forceDelete() |
bool |
Permanent delete |
restore() |
bool |
Restore soft-deleted |
refresh() |
self |
Reload from DB |
fresh() |
?static |
Fresh instance |
trashed() |
bool |
Is soft-deleted |
exists() |
bool |
Persisted in DB |
isDirty($attr = null) |
bool |
Has unsaved changes |
touch() |
bool |
Update updated_at
|
increment($col, $n) |
int |
Increment column |
decrement($col, $n) |
int |
Decrement column |
fill(array) |
self |
Mass assign fillable |
forceFill(array) |
self |
Mass assign all |
toArray() |
array |
Casted attributes |
toJson($opts) |
string |
JSON string |
| Method | Returns | Description |
|---|---|---|
builder($table) |
self |
Static factory |
select(array) |
self |
Set columns |
distinct() |
self |
DISTINCT query |
join($t,$f,$o,$s,$type) |
self |
JOIN |
leftJoin($t,$f,$o,$s) |
self |
LEFT JOIN |
where($c,$o,$v,$bool) |
self |
WHERE |
orWhere($c,$o,$v) |
self |
OR WHERE |
whereIn($c,array,$bool) |
self |
WHERE IN |
whereNull($c,$bool) |
self |
IS NULL |
whereDateRange($c,$s,$e) |
self |
BETWEEN range |
whereCurrentWeek($c) |
self |
Current week |
whereCurrentMonth($c) |
self |
Current month |
whereCurrentYear($c) |
self |
Current year |
orderBy($c,$dir) |
self |
ORDER BY |
groupBy($c) |
self |
GROUP BY |
limit($n) |
self |
LIMIT |
offset($n) |
self |
OFFSET |
insert(array) |
self |
INSERT action |
update(array) |
self |
UPDATE action |
delete() |
self |
DELETE action |
get() |
array |
Execute SELECT |
first() |
?array |
First row |
execute($sql) |
array |
Execute |
count($c,$distinct) |
int |
COUNT |
sum($c) |
mixed |
SUM |
avg($c) |
mixed |
AVG |
min($c) |
mixed |
MIN |
max($c) |
mixed |
MAX |
-
Explicitly define
$fillablefor every model that allows mass assignment. -
Use
$caststo keep your domain types clean — never rely on raw DB strings. -
Cast dates to
datetimeso you getDateTimeHandlerinstances. - Use soft deletes for user-facing data that may need recovery.
- Tag your cache with the model/table name for reliable invalidation.
-
Use
firstOrCreateto avoid race-condition duplicates on unique columns. - Wrap multi-table operations in transactions when consistency matters.
- Don't set
$guarded = []— that's an anti-pattern. Use$fillable. - Don't forget
$softDelete = trueand thedeleted_atcolumn. - Don't call
execute()onget()—get()already executes. - Don't mix
QueryBuilder::builder()state between operations — builders reset after execution. - Don't compare casted datetimes with
===; use->getTimestamp()orisDirty().
-
Select only needed columns:
->select(['id', 'name'])reduces transfer overhead. -
Use indexed columns in
WHEREandJOINclauses. -
Prefer
count()over fetching all rows when you only need a total. -
Use
limit()on list endpoints — never return unbounded sets. - Enable caching on read-heavy models with sensible TTLs.
ResourceGenerator refuses to overwrite files. Delete the existing file or use a different name.
Most likely a model event listener returned false. Check your model.saving or model.creating listeners.
You must define $fillable. With $guarded = ['*'] (default), nothing is mass-assignable. Use forceFill() for bypassing.
If you enable $softDelete = true, run a migration adding:
ALTER TABLE your_table ADD COLUMN deleted_at DATETIME NULL;- Confirm the primary key column matches
$primaryKey. - If soft deletes are on,
find()excludes trashed records — usewithTrashed()->find($id).
Set $timezone correctly on your model. The DB stores Y-m-d H:i:s in $dateFormat, and DateTimeHandler will interpret/return times in $timezone.
The current implementation clones the sub-builder and merges bindings after compilation. If you see parameter mismatches, ensure nested closures don't also call where on the parent outside the closure.
Every execute() calls reset() in a finally block. If you clone a builder mid-flight and reuse it, call reset() or construct a fresh one.
Machinjiri Docs
- Home
- Learn
- Build
-
Tutorials
- Routing
- Controllers and Middleware
- Views and Templates
- Database ORM
- Eloquent Database ORM
- Errors and Exceptions
- Forms and Validation
- Http
- Events and Logging
- Services and DI
- Security
- Authentication
- Caching
- File System
- Date and Time
- Debugging
- Queue and Jobs
- Task Scheduling
- Transport (Mail, SMS)
- LDAP
- Notifications
- Webhooks
- UUID Generations
- Terminal
- Helper Function
- Reference