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:

$post = \App\Models\Post::first();
 
// Set meta fluently for any key – `likes` is no column of `Post`.
$post->likes = 24;
 
// Or use the `setMeta` method.
$post->setMeta('likes', 24);
 
// Set multiple values
$model->setMeta([
'hide' => true,
'color' => '#000',
'likes' => 24,
]);
 
// You may also schedule changes, for example, change the meta in 2 years:
$post->setMetaAt('likes', 6000, '+2 years');

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

class Post extends Model
{
use HasMeta;
 
protected array $metaKeys = [
'color',
'hide',
];
 
// You can use typecast array keys
protected array $metaKeys = [
'foo',
'count' => 'integer',
'color' => 'string',
'hide' => 'boolean',
];
 
}

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.