Installation:
composer require kolossal-io/laravel-multiplex
Publish the migration and config:
php artisan vendor:publish --provider="Kolossal\Multiplex\MultiplexServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="Kolossal\Multiplex\MultiplexServiceProvider" --tag="config"
Run migrations:
php artisan migrate
First Use Case:
Attach versioned metadata to an Eloquent model (e.g., Post):
use Kolossal\Multiplex\Multiplexable;
class Post extends Model implements Multiplexable
{
use \Kolossal\Multiplex\HasMultiplex;
}
Add metadata to a model instance:
$post = Post::find(1);
$post->multiplex()->attach('views', 150, now()); // (key, value, timestamp)
Key Files to Review:
config/multiplex.php (default TTL, storage engine)app/Models/YourModel.php (implement Multiplexable trait)database/migrations/ (check the multiplex_entries table structure)Attaching Metadata:
// Single attachment
$model->multiplex()->attach('analytics.clicks', 42, now());
// Bulk attachment (with timestamps)
$model->multiplex()->attachMany([
['key' => 'analytics.likes', 'value' => 10, 'timestamp' => now()],
['key' => 'analytics.shares', 'value' => 5, 'timestamp' => now()->subHour()],
]);
Querying Metadata:
// Get latest value for a key
$views = $model->multiplex()->get('views');
// Get all versions of a key (ordered by timestamp)
$history = $model->multiplex()->getHistory('views');
// Filter by timestamp range
$recent = $model->multiplex()->whereBetween('timestamp', [
now()->subDays(7),
now()
])->get('views');
Model Events: Leverage built-in events for lifecycle hooks:
// In your model's boot method
static::created(function ($model) {
$model->multiplex()->attach('created_at_metadata', 'initial', now());
});
Scopes: Add custom scopes to filter models by multiplex data:
class PostScope
{
public function scopeWithHighViews($query, $threshold)
{
return $query->whereHas('multiplex', function ($q) use ($threshold) {
$q->where('key', 'views')
->where('value', '>=', $threshold)
->orderBy('timestamp', 'desc')
->limit(1);
});
}
}
Usage:
Post::withHighViews(100)->get();
Caching: Cache frequently accessed multiplex data:
// Cache for 1 hour
$cachedViews = Cache::remember("post.{$post->id}.views", now()->addHour(), function () use ($post) {
return $post->multiplex()->get('views');
});
API Responses: Serialize multiplex data in API responses:
public function toArray()
{
return [
'id' => $this->id,
'multiplex' => $this->multiplex()->getAll(),
];
}
Admin Panels: Use with Laravel Nova or Filament for visualizing multiplex data:
// Nova Tool example
public function fields(Request $request)
{
return array_merge(parent::fields($request), [
MultiplexField::make('Analytics', 'analytics'),
]);
}
Jobs/Queues: Offload multiplex updates to queues:
UpdatePostAnalytics::dispatch($post, ['views' => 150]);
Job:
public function handle()
{
$this->post->multiplex()->attach('views', $this->data['views'], now());
}
Testing: Use factories to seed multiplex data:
$post = Post::factory()->create();
$post->multiplex()->attach('views', 100, now()->subDay());
Key Collisions:
Views vs views.analytics.views).Timestamp Handling:
now(). Ensure your application’s timezone is set in .env:
APP_TIMEZONE=UTC
$model->multiplex()->attach('key', 'value', Carbon::parse('2023-01-01'));
Memory Usage:
getHistory()) can be memory-intensive.$history = $model->multiplex()
->where('key', 'views')
->orderBy('timestamp', 'desc')
->paginate(100);
Database Locking:
DB::transaction(function () use ($model) {
$model->multiplex()->attach('views', 1);
});
Model Deletion:
deleted() model event:
static::deleted(function ($model) {
$model->multiplex()->delete();
});
Query Logging: Enable Laravel’s query log to inspect multiplex queries:
DB::enableQueryLog();
$model->multiplex()->get('views');
dd(DB::getQueryLog());
Common Errors:
multiplex_entries table exists.multiplex_entries table structure matches the package’s expectations (run php artisan vendor:publish again if needed).Multiplexable and uses the HasMultiplex trait.Performance:
multiplex_entries table for large datasets:
Schema::table('multiplex_entries', function (Blueprint $table) {
$table->index(['model_type', 'model_id', 'key']);
$table->index(['timestamp']);
});
Custom Storage Engines:
Extend the Kolossal\Multiplex\Contracts\MultiplexStorage interface to use Redis or another driver:
class RedisMultiplexStorage implements MultiplexStorage
{
public function get($model, $key)
{
return Redis::hGet("multiplex:{$model->getKey()}", $key);
}
// Implement other methods...
}
Register in config/multiplex.php:
'storage' => \App\Multiplex\RedisMultiplexStorage::class,
Event Customization: Listen to multiplex events for analytics or notifications:
Multiplex::attached(function ($model, $key, $value, $timestamp) {
event(new MultiplexUpdated($model, $key, $value));
});
Validation: Add validation rules for multiplex keys/values:
use Kolossal\Multiplex\Rules\MultiplexKey;
$request->validate([
'multiplex_key' => ['required', new MultiplexKey],
'multiplex_value' => 'sometimes|integer',
]);
API Resources: Create a dedicated resource for multiplex data:
class MultiplexResource extends JsonResource
{
public function toArray($request)
{
return [
'key' => $this->key,
'value' => $this->value,
'timestamp' => $this->timestamp->toIso8601String(),
];
}
}
How can I help you explore Laravel packages today?