This package is designed to manage metadata in Laravel projects.
composer require jobmetric/laravel-metadata
This package offers a robust and flexible metadata system for Laravel Eloquent models, enabling you to attach dynamic key-value data through a morphMany
relationship. It supports full control over metadata keys, validation, events, and batch operations.
Before using the package, run:
php artisan migrate
Add the HasMeta
trait to your model:
use JobMetric\Metadata\HasMeta;
class User extends Model
{
use HasMeta;
}
To restrict metadata keys, define a protected array $metadata = [...]
in your model:
class User extends Model
{
use HasMeta;
protected array $metadata = [
'first_name',
'last_name',
'bio',
'birthday',
];
}
If omitted or set as ['*']
, all keys are allowed.
$user = User::find(1);
$user->storeMetadata('phone', '1234567890');
$user->storeMetadataBatch([
'phone' => '1234567890',
'address' => '123 Main St',
]);
$phone = $user->getMetadata('phone');
$allMetadata = $user->getMetadata();
$hasPhone = $user->hasMetadata('phone');
$user->forgetMetadata('phone');
$user->forgetMetadata();
$user->mergeMeta(['nickname', 'website']);
$user->removeMetaKey('bio');
This package includes events for metadata operations:
Event | Description |
---|---|
MetadataStoringEvent |
Before metadata is stored |
MetadataStoredEvent |
After metadata is stored |
MetadataDeletingEvent |
Before metadata is deleted |
MetadataDeletedEvent |
After metadata is deleted |
You may listen to these events to customize your logic.
- If you define
$metadata
in the model, it overrides the default['*']
. - During model
saving
, metadata is validated against allowed keys. - You can interact with the
metas()
relationship directly for advanced queries. - All metadata values that are arrays are stored as JSON in the DB.
Thank you for considering contributing to Laravel Metadata! See the CONTRIBUTING.md for details.
The MIT License (MIT). See the License File for details.