Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Multiplex Laravel Package

kolossal-io/laravel-multiplex

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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
    
  2. 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)
    
  3. 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)

Implementation Patterns

Core Workflows

  1. 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()],
    ]);
    
  2. 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');
    
  3. 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());
    });
    
  4. 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();
    
  5. 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');
    });
    

Integration Tips

  1. API Responses: Serialize multiplex data in API responses:

    public function toArray()
    {
        return [
            'id' => $this->id,
            'multiplex' => $this->multiplex()->getAll(),
        ];
    }
    
  2. 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'),
        ]);
    }
    
  3. 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());
    }
    
  4. Testing: Use factories to seed multiplex data:

    $post = Post::factory()->create();
    $post->multiplex()->attach('views', 100, now()->subDay());
    

Gotchas and Tips

Pitfalls

  1. Key Collisions:

    • Multiplex keys are case-sensitive. Avoid duplicates like Views vs views.
    • Fix: Use a consistent naming convention (e.g., analytics.views).
  2. Timestamp Handling:

    • If timestamps are not provided, the package uses now(). Ensure your application’s timezone is set in .env:
      APP_TIMEZONE=UTC
      
    • Fix: Explicitly pass timestamps for consistency:
      $model->multiplex()->attach('key', 'value', Carbon::parse('2023-01-01'));
      
  3. Memory Usage:

    • Fetching large histories (e.g., getHistory()) can be memory-intensive.
    • Fix: Use cursors or pagination:
      $history = $model->multiplex()
          ->where('key', 'views')
          ->orderBy('timestamp', 'desc')
          ->paginate(100);
      
  4. Database Locking:

    • Concurrent writes to the same multiplex key may cause race conditions.
    • Fix: Use database transactions:
      DB::transaction(function () use ($model) {
          $model->multiplex()->attach('views', 1);
      });
      
  5. Model Deletion:

    • Deleting a model does not automatically purge its multiplex entries.
    • Fix: Override the deleted() model event:
      static::deleted(function ($model) {
          $model->multiplex()->delete();
      });
      

Debugging Tips

  1. Query Logging: Enable Laravel’s query log to inspect multiplex queries:

    DB::enableQueryLog();
    $model->multiplex()->get('views');
    dd(DB::getQueryLog());
    
  2. Common Errors:

    • "Table not found": Run migrations or check the multiplex_entries table exists.
    • "Column not found": Verify the multiplex_entries table structure matches the package’s expectations (run php artisan vendor:publish again if needed).
    • "Call to undefined method": Ensure your model implements Multiplexable and uses the HasMultiplex trait.
  3. Performance:

    • Add indexes to the multiplex_entries table for large datasets:
      Schema::table('multiplex_entries', function (Blueprint $table) {
          $table->index(['model_type', 'model_id', 'key']);
          $table->index(['timestamp']);
      });
      

Extension Points

  1. 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,
    
  2. Event Customization: Listen to multiplex events for analytics or notifications:

    Multiplex::attached(function ($model, $key, $value, $timestamp) {
        event(new MultiplexUpdated($model, $key, $value));
    });
    
  3. Validation: Add validation rules for multiplex keys/values:

    use Kolossal\Multiplex\Rules\MultiplexKey;
    
    $request->validate([
        'multiplex_key' => ['required', new MultiplexKey],
        'multiplex_value' => 'sometimes|integer',
    ]);
    
  4. 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(),
            ];
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours