/ Model

ORM Model

Miko ORM allows you to represent database tables as PHP classes with fluent syntax.


Model Properties

Property Type Description
$tablestringTable name
$primaryKeystringPrimary key column (default: Id)
$fillablearrayMass assignable fields
$guardedarrayProtected from mass assignment
$hiddenarrayHidden in toArray/toJson
$castsarrayType casting (boolean, integer, array, datetime)

Defining a Model

use Miko\Database\ORM\Model;
use Miko\Database\ORM\Traits\{HasTimestamps, SoftDeletes};

class User extends Model
{
    use HasTimestamps, SoftDeletes;
    
    protected static string $table = 'users';
    protected string $primaryKey = 'Id';
    
    protected array $fillable = ['Name', 'Email', 'Password', 'Role'];
    protected array $hidden = ['Password'];
    protected array $casts = [
        'IsActive' => 'boolean',
        'Age' => 'integer',
        'Settings' => 'array'
    ];
}

CRUD Operations

Create

// Method 1: Create and save
$user = User::create([
    'Name' => 'John Doe',
    'Email' => 'john@example.com',
    'Password' => password_hash('secret', PASSWORD_DEFAULT)
]);

// Method 2: New instance then save
$user = new User();
$user->Name = 'John Doe';
$user->Email = 'john@example.com';
$user->save();

// Method 3: Fill and save
$user = new User();
$user->fill(['Name' => 'John', 'Email' => 'john@example.com']);
$user->save();

Read

// Find by ID
$user = User::find(1);

// Find or throw exception
$user = User::findOrFail(1);

// Find multiple
$users = User::findMany([1, 2, 3]);

// Get all
$users = User::all();

// Get first
$user = User::first();
$user = User::where('Email', 'john@example.com')->first();

// Grouped where — WHERE IsActive = ? AND (Role = ? OR Role = ?)
$staff = User::where('IsActive', true)
    ->where(function ($q) {
        $q->where('Role', 'admin')
          ->orWhere('Role', 'moderator');
    })
    ->get();

Update

// Method 1: Find and update
$user = User::find(1);
$user->Name = 'John Updated';
$user->save();

// Method 2: Mass update
User::where('Role', 'guest')->update(['Role' => 'user']);

// Method 3: Update or create
$user = User::updateOrCreate(
    ['Email' => 'john@example.com'],  // Find by
    ['Name' => 'John Doe', 'Role' => 'admin']  // Update/Create with
);

Delete

// Delete single
$user = User::find(1);
$user->delete();

// Delete by ID
User::destroy(1);
User::destroy([1, 2, 3]);

// Delete with condition
User::where('IsActive', false)->delete();

Soft Deletes

use Miko\Database\ORM\Traits\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

// Soft delete (sets DeletedAt)
$user->delete();

// Check if soft deleted
if ($user->trashed()) {
    echo "User is deleted";
}

// Restore
$user->restore();

// Force delete (permanent)
$user->forceDelete();

// Include soft deleted in queries
$users = User::withTrashed()->get();

// Only soft deleted
$users = User::onlyTrashed()->get();

Timestamps

use Miko\Database\ORM\Traits\HasTimestamps;

class User extends Model
{
    use HasTimestamps;
    
    // Automatically manages:
    // - CreatedDate (set on create)
    // - UpdatedDate (set on create/update)
}

// Disable timestamps for specific operation
$user->timestamps = false;
$user->save();

Accessors & Mutators

class User extends Model
{
    // Accessor: get{AttributeName}Attribute
    public function getFullNameAttribute(): string
    {
        return $this->FirstName . ' ' . $this->LastName;
    }
    
    // Mutator: set{AttributeName}Attribute
    public function setPasswordAttribute(string $value): void
    {
        $this->attributes['Password'] = password_hash($value, PASSWORD_DEFAULT);
    }
}

// Usage
$user->FullName;  // Calls accessor
$user->Password = 'secret';  // Calls mutator

Serialization

// To array
$array = $user->toArray();

// To JSON
$json = $user->toJson();

// Only specific fields
$data = $user->only('Id', 'Name', 'Email');

// Except specific fields
$data = $user->except('Password', 'RememberToken');

// Temporarily show hidden
$data = $user->makeVisible('Password')->toArray();

// Temporarily hide
$data = $user->makeHidden('Email')->toArray();

Model Events

class User extends Model
{
    protected static function boot(): void
    {
        parent::boot();
        
        static::creating(function($user) {
            $user->Role = 'user';
        });
        
        static::created(function($user) {
            // Send welcome email
        });
        
        static::updating(function($user) {
            // Log changes
        });
    }
}