whilesmart/eloquent-metadata
Composer 安装命令:
composer require whilesmart/eloquent-metadata
包简介
Reusable metadata json column and helpers for Eloquent models
README 文档
README
A reusable metadata bag for Eloquent models: dot-notation get/set helpers, a query scope, and two interchangeable storage strategies. Use it to hold values that are unlikely or awkward as first-class table columns, keeping the core schema clean and extensible.
Installation
composer require whilesmart/eloquent-metadata
The service provider is auto-discovered. Optionally publish the config:
php artisan vendor:publish --tag=metadata-config
Two storage strategies
| Strategy | Where it stores | When to use |
|---|---|---|
column (default) |
a json column on the model's own table | per-model bag, fewer joins, queries stay on the row |
table |
rows in one shared polymorphic model_metadata table |
no schema change per model; one place for all metadata |
Set the default for the whole app in config/metadata.php, or override per model.
Column strategy
Add the column in a migration with the Blueprint macro, then add the trait:
Schema::create('phases', function (Blueprint $table) { $table->id(); $table->string('name'); $table->metadata(); // nullable json column $table->timestamps(); });
use Whilesmart\Metadata\Traits\HasMetadata; class Phase extends Model { use HasMetadata; // uses config('metadata.strategy'), 'column' by default }
Table strategy
No column needed. The package ships the shared model_metadata table migration (disable with register_table_migration => false). Override the strategy on the model:
use Whilesmart\Metadata\Traits\HasMetadata; class Agent extends Model { use HasMetadata; protected $metadataStrategy = 'table'; }
To make table the app-wide default instead, set 'strategy' => 'table' in the config.
Helpers (identical for both strategies)
$model->setMeta('billing.rate', 120); $model->getMeta('billing.rate'); // 120 $model->getMeta('missing', 'default'); // 'default' $model->getMeta(); // the whole array Model::whereMeta('billing.rate', 120)->get();
Persistence note
- column:
setMeta()mutates the attribute; callsave()to persist (like any Eloquent attribute). - table:
setMeta()writes the shared row immediately viaupdateOrCreate.
Configuration
config/metadata.php:
return [ 'strategy' => 'column', // 'column' | 'table' 'column' => 'metadata', // column name for the column strategy 'table' => 'model_metadata', // shared table name for the table strategy 'register_table_migration' => true, ];
License
MIT
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-07-11