Attach Time-sliced Metadata to Eloquent Models

Packages

November 11th, 2022

Attach Time-sliced Metadata to Eloquent Models

Laravel Multiplex is a Laravel package to attach time-sliced metadata to Eloquent models. With the v1.0 release near, here are the main features:

  • Metadata is saved in versions, including the ability to schedule metadata for the future
  • Fluent syntax
  • East to try extending your model with versionable metadata without touching original columns
  • Type conversion system
  • Configurable

Here are a few basic examples of how this package looks working with a model:

1$post = \App\Models\Post::first();
2 
3// Set meta fluently for any key – `likes` is no column of `Post`.
4$post->likes = 24;
5 
6// Or use the `setMeta` method.
7$post->setMeta('likes', 24);
8 
9// Set multiple values
10$model->setMeta([
11 'hide' => true,
12 'color' => '#000',
13 'likes' => 24,
14]);
15 
16// You may also schedule changes, for example, change the meta in 2 years:
17$post->setMetaAt('likes', 6000, '+2 years');

You can also limit which meta keys are allowed on a model with a $metaKeys property:

1class Post extends Model
2{
3 use HasMeta;
4 
5 protected array $metaKeys = [
6 'color',
7 'hide',
8 ];
9 
10 // You can use typecast array keys
11 protected array $metaKeys = [
12 'foo',
13 'count' => 'integer',
14 'color' => 'string',
15 'hide' => 'boolean',
16 ];
17 
18}

When you set up this package, read the performance section to avoid N+1 queries. To learn more about this package and get full installation instructions, check out the laravel-metadata on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.