Anvyr Docs
Documentation menu Anvyr Loom 1.x
Anvyr Loom

Version 1.x

← All documentation

GuideAnvyr Loom 1.xDeveloper

Models and persistence

Define a model, persist records, cast attributes, and handle deletion explicitly.

On this page

Prepare the table and model

This example uses the notes table from migrations and schema. Put the class in user/modules/Notes/src/Models/Note.php in a Notes module, whose Composer mapping loads the Notes namespace.

<?php

namespace Notes\Models;

use Anvyr\Loom\Database\Concerns\SoftDeletes;
use Anvyr\Loom\Database\Model;
use Anvyr\Loom\Database\ModelBuilder;
use Anvyr\Loom\Database\Relations\BelongsTo;
use Anvyr\Loom\Database\Relations\BelongsToMany;

class Note extends Model
{
    use SoftDeletes;

    protected ?string $table = 'notes';
    protected array $fillable = ['title', 'body', 'archived', 'settings', 'author_id'];
    protected array $casts = ['archived' => 'bool', 'settings' => 'array'];

    public function scopeActive(ModelBuilder $query): void
    {
        $query->where('archived', '=', 0);
    }

    public function author(): BelongsTo
    {
        return $this->belongsTo(Author::class, 'author_id');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class, 'note_tag', 'note_id', 'tag_id');
    }
}

The relationship classes are defined in relationships; they are needed when loading those relations, not for the standalone CRUD example below. The application bootstrap registers the model connection resolver. Read database settings under db, in user/config/db.php, rather than database.php.

Create and retrieve a record

use Notes\Models\Note;

$note = Note::create([
    'title' => 'A field note',
    'body' => 'Keep the source close.',
    'archived' => false,
    'settings' => ['layout' => 'plain'],
]);

$loaded = Note::query()->find($note->getKey());
$layout = $loaded->settings['layout']; // plain

create() inserts and returns a model with its generated key. find() and first() return a model or null; get() returns a Collection of models. Check for null when looking up external IDs.

Models populate created_at and updated_at by default. Add these columns using timestamps(), or explicitly set protected bool $timestamps = false for a table without them.

Update only what changed

$note->title = 'A revised field note';
$changed = $note->isDirty('title'); // true
$note->save();

$note->update(['archived' => true]);
$active = Note::query()->active()->get();

update() fills allowed attributes and saves. Direct property assignment also changes attributes; $fillable guards mass assignment through construction, fill(), create(), and update(), not every possible write. Models start with $guarded = ['*'], so declare allowed fields deliberately.

Supported casts include integer, float, boolean, string, array/JSON, date, and datetime. Array/JSON casts encode arrays for storage and decode strings on access. A cast does not validate application input.

Soft delete is an explicit operation

$note->softDelete();
$hidden = Note::query()->find($note->getKey()); // null
$trashed = Note::query()->withTrashed()->find($note->getKey());
$onlyTrashed = Note::query()->onlyTrashed()->get();
$trashed->restore();

The trait adds a default deleted_at IS NULL scope, plus withTrashed() and onlyTrashed(). The table needs a nullable deleted_at column.

delete() still performs a physical delete, even on a model using this trait. forceDelete() delegates to that physical operation. Use softDelete() when you want a recoverable record.

Know which operations run model behavior

Instance saves and deletes dispatch model events such as model.creating, model.created, model.updating, and model.deleted through the application event dispatcher. Builder-level update() and delete() are SQL mutations; they do not instantiate each affected record to run its casts or lifecycle events.

Use a fresh builder per independent query: terminal methods can change limits or other query state. See queries and transactions for pagination and bulk work.

Verified against Model, HasAttributes, and SoftDeletes.

Continue readingModel relationships