jobmetric / laravel-metadata
This package is for the metadata of different Laravel projects.
Requires
- php: >=8.0.1
- jobmetric/laravel-custom-field: ^1.7
- jobmetric/laravel-package-core: ^1.22
- laravel/framework: >=9.19
Requires (Dev)
- mockery/mockery: ^1.4.4
- orchestra/testbench: ^8.36
- phpunit/phpunit: ^10.1
README
Metadata for Laravel
This package is designed to manage metadata in Laravel projects.
Install via Composer
composer require jobmetric/laravel-metadata
Documentation
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.
Migrate database
Before using the package, run:
php artisan migrate
How to use
Attach Trait to Model
Add the HasMeta
trait to your model:
use JobMetric\Metadata\HasMeta; class User extends Model { use HasMeta; }
Optional: Limit Allowed Metadata Keys
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.
API Usage
Store metadata
$user = User::find(1); $user->storeMetadata('phone', '1234567890');
Store multiple metadata
$user->storeMetadataBatch([ 'phone' => '1234567890', 'address' => '123 Main St', ]);
Retrieve a metadata value
$phone = $user->getMetadata('phone');
Retrieve all metadata
$allMetadata = $user->getMetadata();
Check if metadata exists
$hasPhone = $user->hasMetadata('phone');
Delete specific metadata
$user->forgetMetadata('phone');
Delete all metadata
$user->forgetMetadata();
Allow additional metadata keys at runtime
$user->mergeMeta(['nickname', 'website']);
Remove allowed metadata key
$user->removeMetaKey('bio');
Events
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.
Advanced Notes
- 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.
Contributing
Thank you for considering contributing to Laravel Metadata! See the CONTRIBUTING.md for details.
License
The MIT License (MIT). See the License File for details.