Data, models and schema ownership

Pulse uses Eloquent models on top of migration-managed tables. A model describes application behaviour; migrations describe actual database columns and constraints. A name in $fillable is not proof that the database has that column. Start from the User reference for a full account example and the model catalogue for every model's declarations and storage configuration.

Choose where data belongs

Information Owner / interface
Account identity, login/security state Core users / User
Pools, balances, progression Core player_stats / PlayerStat; money through EconomyService
Plugin installation/runtime state Core installed_plugins / InstalledPlugin
Shared settings Core settings / SettingService
Extension-specific values on an existing model plugin_metadata / PluginMetadata, or your own plugin table
Complex game records and relationships Plugin-owned tables and migrations
Marketplace purchase and vendor state Not a core account field

Core must not import plugin model classes. A plugin may depend on the generic core, declare another plugin dependency, or use documented hooks/interfaces. Keep game-specific columns out of core users and other shared schemas.

Core model map

Model(s) Table / responsibility Guide
User users, identity Complete class reference
PlayerStat, EconomyTransaction player_stats, economy_transactions Economy/state
InstalledPlugin installed_plugins, single runtime registry Plugins
PluginMetadata plugin_metadata, polymorphic JSON values This page
Setting settings, key/value configuration Configuration
Notification, AdminNotification Player and staff notifications Communication
EmailSetting, EmailTemplate Delivery settings and templates Communication
OAuthProvider Provider-linked accounts User, security
LicenseKey Optional per-package licensing state Packages
Webhook, WebhookDelivery Endpoints and delivery history Communication
ApiKey, ApiRequestLog Managed integration keys and request records Security
IpBan IP match rules Security
DeviceFingerprint, MultiAccountCluster, MultiAccountClusterMember Multi-account investigation data Security
ErrorLog Captured exception/error records Operations
StaffChatMessage, StaffChatReadStatus Staff messages/read markers Communication
AnnouncementType Configurable announcement categories Communication

Framework tables additionally store permissions/pivots, tokens, password-reset tokens, sessions, queued/failed jobs and caches. Activity logging uses its service/table without a dedicated core ActivityLog model. See all migration definitions before assuming foreign-key deletion rules or column types.

Find and save model data

Eloquent examples run in a booted PHP backend. Select explicit fields, whitelist input and decide who is allowed to act before saving:

use App\Core\Models\User;

$users = User::query()
    ->with('roles')
    ->where('is_banned', false)
    ->orderBy('id')
    ->paginate(25);

This returns a paginator. first() returns a model/null; firstOrFail() and findOrFail() throw when absent. Collection queries do not authorize access to all matching records.

fill() obeys mass-assignment rules and changes memory; save() persists. update() combines the two. Query-builder updates operate directly on stored rows and bypass model setters/events. A missing field can be a selection issue under strict mode; a missing database column is a schema issue.

Pulse enables strict model behaviour outside production. Eager-load relationships and select attributes that security checks require. Do not remove strictness just to silence a mistaken relationship or field name.

PluginMetadata reference

Resolve this model directly:

use App\Core\Models\PluginMetadata;

PluginMetadata::setValue($user, 'my-plugin', 'tutorial_complete', true);
$complete = PluginMetadata::getValue($user, 'my-plugin', 'tutorial_complete', false);

$user must be a saved model that your handler has permission to edit. Expected result: a row keyed by owner class, owner ID, plugin slug and key; $complete is boolean true after JSON casting.

Fields and ownership

Field Meaning
owner_type, owner_id Class name and primary key of the owning model.
plugin_id Extension slug; not an installed_plugins numeric ID.
key Value name within the extension namespace.
value JSON-cast value: scalar, array or null.
id, created_at, updated_at Record identity/timestamps.

owner() returns a polymorphic inverse relation. The static helpers use get_class($owner) when storing/querying owner type. A custom morph map or subclass changes that contract; validate it before mixing direct helpers and alternative relation representations.

Static methods

All write helpers persist immediately. They do not validate the caller's account permission.

Method Arguments/defaults Return
getValue(Model $owner, string $pluginId, string $key, mixed $default = null) Existing owner, plugin/key, fallback Stored mixed value or fallback when no record exists. Stored null is returned as null.
setValue(Model $owner, string $pluginId, string $key, mixed $value) JSON-compatible value Stored PluginMetadata; update-or-create on the owner/plugin/key tuple.
deleteValue(Model $owner, string $pluginId, string $key) Tuple Boolean: any row deleted.
getAllForPlugin(Model $owner, string $pluginId) Owner/plugin Associative key/value array.
deleteAllForPlugin(Model $owner, string $pluginId) Owner/plugin Integer number deleted.
incrementValue(Model $owner, string $pluginId, string $key, int $amount = 1) Amount to add; missing value starts at 0 New integer value.
decrementValue(Model $owner, string $pluginId, string $key, int $amount = 1) Amount to subtract New integer value.

incrementValue() casts the current value to int, computes a new value and saves it. It is not an atomic database increment and can lose concurrent changes. Use a transactional plugin table for counters that require exact concurrency guarantees; use the economy service for money.

Query scopes

$rows = PluginMetadata::forOwner($user)
    ->forPlugin('my-plugin')
    ->withKey('tutorial_complete')
    ->get();

forOwner($owner), forPlugin($pluginId) and withKey($key) return a builder, allowing more filters. The concrete implementations are scopeForOwner, scopeForPlugin and scopeWithKey; do not pass the builder yourself when calling the scope through Eloquent.

HasPluginMetadata trait

App\Core\Traits\HasPluginMetadata can be applied to your own model class. Current core User imports its name but does not use the trait, so do not assume its instance methods are on User.

Trait method Behaviour
pluginMetadata(): MorphMany Owner relationship.
getPluginMeta($pluginId, $key, $default = null) Reads using getValue().
setPluginMeta($pluginId, $key, $value): static Persists value, returns the owner model.
hasPluginMeta($pluginId, $key): bool Whether the tuple exists, including null values.
deletePluginMeta($pluginId, $key): bool Deletes one value.
getAllPluginMeta($pluginId): array All values for that plugin/owner.
setManyPluginMeta($pluginId, array $data): static Writes each key individually; not one transaction by itself.
deleteAllPluginMeta($pluginId): int Removes all values for that plugin/owner.
incrementPluginMeta($pluginId, $key, $amount = 1): int Non-atomic helper increment.
decrementPluginMeta($pluginId, $key, $amount = 1): int Non-atomic helper decrement.
getOrSetPluginMeta($pluginId, $key, callable $default): mixed If value resolves to null, invokes callback with owner, persists result. A stored null also triggers this path.
withPluginMeta($pluginId, $key, $value = null) Scope requiring metadata; non-null values compare to JSON encoding.
withoutPluginMeta($pluginId, $key) Scope excluding that plugin/key.

The default callback is a convenience, not an atomic once-only initialization mechanism. Missing trait methods are not fixed by merely importing the trait's namespace at file top; the class must apply it or a plugin must deliberately add a macro.

Migrations and schema changes

Core migrations live in backend/database/migrations/. Product migrations can be loaded from its product/ child. Plugins load their own migration paths through the plugin infrastructure. Read plugin lifecycle before assuming disabled packages' migration paths are absent.

A migration changes the schema, while a seeder writes starting data. Neither is a supported substitute for manually changing production rows as part of every application boot. Back up and test upgrades against a copy before live changes.

php artisan migrate:status is a useful read-only inspection. migrate applies outstanding changes. migrate:fresh, rollback/reset and database-wipe commands destroy or reverse state; this handbook does not use them for routine setup verification. See operations for environment restrictions.

Portability and correctness

Tests use SQLite :memory:. Local Docker uses MySQL; production uses MariaDB. Prefer Eloquent/query-builder expressions that compile for both. If raw SQL is unavoidable, branch on driver and verify the production-driver path explicitly. A passing SQLite test cannot prove JSON-function, collation, row-lock or unsigned-integer semantics.

Use transactions for related state changes, unique constraints for invariants and locks when a request reads then modifies a shared value. Foreign keys enforce only the relationships actually declared. Polymorphic metadata does not automatically acquire a foreign key to every possible owner table.

Troubleshooting

Symptom Check
Unknown column Migration history and actual schema; compare model fillable fields to migrations.
Missing attribute exception Query selected too few fields; load the fields the code reads.
Relationship not found Verify the method exists on the current model; imported traits are not applied traits.
Duplicate records under load Unique constraints and concurrent initialization logic.
Stale relationship data Reload/fresh the model or relationship after the mutation.
Data lost after parallel JSON writes Serialize updates or use normalized, locked rows.

Source reference

Models, migrations/seeders, PluginMetadata, HasPluginMetadata, User, Economy. Source references expose declarations and storage definitions; they do not establish every lifecycle side effect or cross-driver behaviour.