Search by

zairakai / laravel-eloquent

zairakai

Enhanced Eloquent model trait for automatic table management, primary key detection, and JSON serialization with column mapping

Package info

gitlab.com/zairakai/php-packages/laravel-eloquent

Issues

Documentation

pkg:composer/zairakai/laravel-eloquent

Fund package maintenance!

Patreon

Other

Statistics

Installs: 89

Dependents: 0

Suggesters: 0

Stars: 0

4.0.0 2026-11-19 18:12 UTC

README

Laravel Eloquent

zairakai/laravel-eloquent

Main Develop Coverage

GitLab Release Packagist Docs Downloads License

PHP Laravel Static Analysis Code Style

Eloquent base classes and helpers for safer column mapping, automatic table detection, and clean JSON serialization.

Documentation: laravel-eloquent-daeeae.gitlab.io

Features

  • Column mapping: use logical names in your code, the model reads and writes the physical columns (COLUMNS).
  • Automatic table and primary key: derived from the class and its folder, with explicit overrides.
  • Deprecated column tracking: redirect a renamed column, with a log line (COLUMNS_DELETED).
  • Safe JSON: toJson() and toReadableArray() follow the rules of toArray() and use logical names.
  • BaseModel, BasePivot and the BaseTable trait: the same behavior on a new class or an existing model.
  • eloquent:convert: converts existing Model and Pivot classes.
  • Opt-in short-lived query cache and configurable logging.

Requirements

PHP 8.4 or higher and Laravel 12 or 13 (illuminate/database and illuminate/support).

Install

composer require zairakai/laravel-eloquent
php artisan vendor:publish --tag=laravel-eloquent-config   # optional

Usage

use Zairakai\LaravelEloquent\Models\BaseModel;

class User extends BaseModel
{
    public const COLUMNS = [
        'id'    => 'user_id',
        'email' => 'user_email',
        'name'  => 'full_name',
    ];
}

User::where('email', 'alice@example.com')->first();
$user->fill(['name' => 'Alice']);
$user->getAttribute('email');
Models, pivots and the trait | Class | Extends | For | | :--- | :--- | :--- | | `BaseModel` | `Model` | models | | `BaseAuthenticatable` | `Illuminate\Foundation\Auth\User` | models that log in (users, admins) | | `BasePivot` | `Pivot` | pivots of `belongsToMany`, non-incrementing | | `BaseMorphPivot` | `MorphPivot` | pivots of `morphToMany`, non-incrementing | All of them use the `BaseTable` trait, which also gives `getIntKey()` and `getStringKey()`: the primary key as an `int` or a `string`, for static analysis. To keep another base class (a model of a vendor package, for example), use the trait yourself: ```php use Illuminate\Database\Eloquent\Model; use Zairakai\LaravelEloquent\Traits\BaseTable; class Post extends Model { use BaseTable; public const COLUMNS = ['id' => 'post_id', 'title' => 'post_title']; } class RoleUser extends BasePivot { public const TABLE_NAME = 'role_user'; public const COLUMNS = ['role_id' => 'fk_role', 'user_id' => 'fk_user']; } ```
Columns, relations and scopes `fill()`, `getAttribute()`, `setAttribute()` and `isFillable()` resolve a logical name to its column. A key that is not in `COLUMNS` is used as it is, and a key that is not a string goes to Eloquent unchanged. `RELATIONS` and `SCOPES` are **resolution helpers only**: they give the name of a relation method or of a scope method for a logical name. They do not change `$model->roles`, `with('roles')` or the call of a scope. ```php User::resolveColumn('email'); // 'user_email' User::resolveRelation('roles'); // the RELATIONS entry, or 'roles' User::resolveScope('suspended'); // the SCOPES entry, or 'suspended' ``` Rename a column and keep the old key in `COLUMNS_DELETED` to redirect legacy code, with a log line: ```php public const COLUMNS = ['id' => 'user_id', 'username' => 'login_name']; public const COLUMNS_DELETED = ['login' => 'username']; // 'login' resolves to 'login_name' ```
Table name and primary key Every folder under `App\Models` segments the models: the folders, in lowercase and joined by `_`, are the prefix of the table name (`App` and `Models` are ignored). `TABLE_NAME` overrides it. ```php // App\Models\User -> users // App\Models\BlogPost -> blog_posts // App\Models\Twitch\User -> twitch_users // App\Models\Auth\User -> auth_users // App\Models\Twitch\Chat\Message -> twitch_chat_messages ``` The primary key is, in this order: the `PRIMARY_KEY` constant, the value of `COLUMNS['id']`, then `'id'`.
JSON serialization `toReadableArray()` is what `toArray()` gives, with logical names: casts, dates, accessors of `$appends`, `$visible` and `$hidden` apply, to the attributes and to the relations. `toJson()` and `jsonSerialize()` use it, and `toJson()` throws a `JsonEncodingException` when the encoding fails, as Eloquent does.
Configuration and logging Key options of `config/laravel-eloquent.php`: | Key | Default | Description | | :--- | :--- | :--- | | `logging.enabled` | `true` | Turn the logging of the column resolution on or off. | | `logging.channel` | `null` | Log channel (the default channel when null). | | `logging.levels.deprecated` | `'warning'` | Level for a deprecated column. | | `logging.levels.missing` | `'info'` | Level for a column that is not in `COLUMNS`. | | `logging.include_backtrace` | `true` | Add a backtrace to the log lines. | | `logging.backtrace_depth` | `5` | Frames of the backtrace. | | `logging.excluded_models` | `[]` | Models left out of the logging. | | `logging.once` | `true` | One line per process for the same type, model and column, instead of one per instance or access. | | `request_cache.enabled` | `false` | Turn the short-lived query cache on. | | `request_cache.ttl` | `1` | Seconds an entry is kept. `0` turns the cache off. | Environment variables: `ELOQUENT_LOGGING_ENABLED`, `ELOQUENT_LOGGING_CHANNEL`, `ELOQUENT_LOG_LEVEL_DEPRECATED`, `ELOQUENT_LOG_LEVEL_MISSING`, `ELOQUENT_LOGGING_BACKTRACE`, `ELOQUENT_LOGGING_BACKTRACE_DEPTH`, `ELOQUENT_LOGGING_ONCE`, `ELOQUENT_REQUEST_CACHE` and `ELOQUENT_REQUEST_CACHE_TTL`.
Short-lived query cache Off by default. With `ELOQUENT_REQUEST_CACHE=true`, identical `SELECT` queries (same connection, SQL and bindings) are served from the `array` cache store for `request_cache.ttl` seconds (1 by default). - It applies to every query of the `mysql`, `pgsql`, `sqlite` and `sqlsrv` connections, not to some models only. - The entries expire by themselves, in a long-lived process too. Laravel Octane also flushes the `array` store before each request (listener `FlushArrayCache`); a queue worker, Horizon or `schedule:work` does not, so only the TTL limits the age of an entry there. - **A write clears nothing**: a query that repeats within the TTL after an `insert`, `update` or `delete` reads the cached result. Keep the TTL short. - A locked read (`lockForUpdate`, `sharedLock`) is never cached. - Eager loading (`with()`) and `Model::preventLazyLoading()` remove most repeated queries at the source: prefer them.
Stubs ```bash php artisan vendor:publish --tag=laravel-eloquent-stubs ``` The stubs are published in the `stubs` folder of the application, where Laravel reads them before its own: - `model.stub` is used by `make:model` and extends `BaseModel`; - `model.pivot.stub` is used by `make:model --pivot` and extends `BasePivot`; - `model.morph-pivot.stub` is used by `make:model --morph-pivot` and extends `BaseMorphPivot`;
Convert existing models ```bash php artisan eloquent:convert --dry-run # preview, nothing is written php artisan eloquent:convert # asks for confirmation php artisan eloquent:convert --path=app/Domain --force # another folder, no question ``` It replaces `extends Model`, `extends Pivot` and `extends MorphPivot` with `BaseModel`, `BasePivot` and `BaseMorphPivot`, updates the imports and removes `use BaseTable`. An import that the file still uses (`Model::unguard()`, a type hint) stays. The converted code is checked before it is written: a file whose result would not be valid PHP is listed as `skipped` and left as it is. An empty `--path` falls back to `app/Models`. The command rewrites files in place: commit your models first.

Development

make quality        # pint + phpstan + rector + insights + markdownlint + shellcheck
make quality-fast   # pint + phpstan + markdownlint
make test           # phpunit

Statistics

Statistics of laravel-eloquent

Contributing

Contributions are welcome. Please read CONTRIBUTING.md for the project-specific workflow and quality standards.

Getting Help

License Security Policy Issues

Made with ❤️ by Zairakai