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 Steps

  1. Installation:
    composer require kolossal-io/laravel-multiplex
    php artisan migrate
    
  2. Attach Trait: Add use Kolossal\Multiplex\HasMeta; to your Eloquent model.
    class Post extends Model
    {
        use HasMeta;
    }
    

First Use Case

Set and retrieve time-sliced metadata on a model:

$post = Post::first();

// Set meta fluently
$post->likes = 24;

// Or use explicit method
$post->setMeta('views', 100);

// Schedule future meta
$post->setMetaAt('likes', 1000, '+1 week');

// Retrieve current meta
$post->likes; // Returns 24 (current value)

Where to Look First

  • README.md: Focus on the "Attaching Metadata" and "Retrieving Metadata" sections.
  • Configuration: Check config/multiplex.php for allowed keys, default types, and event settings.
  • Events: Review Kolossal\Multiplex\Events for customization hooks.

Implementation Patterns

Core Workflows

  1. Fluent Metadata Handling: Use dynamic properties for simplicity:

    $user->premium = true; // Automatically saved as meta
    
  2. Time-Sliced Updates: Schedule future or past changes:

    $user->saveMetaAt('subscription', 'cancelled', '+30 days');
    
  3. Batch Operations: Update multiple keys at once:

    $post->setMeta([
        'views' => 500,
        'likes' => 100,
        'comments' => 5
    ]);
    
  4. Conditional Retrieval: Use getMeta() with fallbacks:

    $post->getMeta('tags', []); // Returns [] if 'tags' doesn't exist
    

Integration Tips

  • Polymorphic Usage: Attach meta to any model without schema changes.
  • Fallback Columns: If a meta key matches a database column, the column value is used as fallback.
  • Type Conversion: Leverage built-in support for enums, UUIDs, and custom types via config/multiplex.php.
  • Query Scopes: Chain scopes for complex queries:
    Post::whereMeta('likes', '>', 100)
         ->whereDoesntHaveMeta('hidden')
         ->get();
    

Advanced Patterns

  1. Time Travel Queries: Retrieve meta as of a specific date:

    $post->metaAt('2023-01-01')->pluck('value', 'key');
    
  2. Event-Driven Extensions: Listen for MetaHasBeenAdded to trigger side effects:

    event(new MetaHasBeenAdded($meta, $model));
    
  3. Custom Validation: Override validateMeta() in your model to enforce rules:

    protected function validateMeta(array $meta): void
    {
        if ($meta['likes'] < 0) {
            throw new \InvalidArgumentException('Likes cannot be negative.');
        }
    }
    
  4. Performance Optimization: Use pluckMeta() for bulk retrieval:

    $posts->pluckMeta(['likes', 'views']); // Returns Collection of arrays
    

Gotchas and Tips

Common Pitfalls

  1. Database Compatibility:

    • Window Functions: Ensure your DB supports ROW_NUMBER() OVER (...) (MySQL 8.0+, PostgreSQL 9.0+, etc.).
    • SQLite: Test thoroughly; window functions may behave differently.
  2. Meta Key Conflicts:

    • Avoid keys matching existing model columns unless you intend to use them as fallbacks.
    • Use metaKeys() to restrict allowed keys:
      $model->metaKeys(['likes', 'views']); // Only these keys allowed
      
  3. Time Zone Handling:

    • published_at uses the system timezone. Explicitly pass Carbon instances for consistency:
      $post->saveMetaAt('event', 'scheduled', Carbon::parse('2023-12-31'));
      
  4. Dirty State Quirks:

    • isMetaDirty() may return true even if no meta was changed if the model itself is dirty.
    • Use saveWithoutMeta() to bypass meta persistence during model saves.
  5. Type Casting Issues:

    • Custom types (e.g., enums) must be registered in config/multiplex.php.
    • Raw queries (whereRawMeta) bypass type casting; use cautiously.

Debugging Tips

  1. Inspect Meta Records: Use allMeta to debug all versions (published/unpublished):

    $post->allMeta->toArray();
    
  2. Check Query Logs: Enable Laravel’s query logging to verify window function usage:

    \DB::enableQueryLog();
    $post->meta; // Inspect generated SQL
    
  3. Validate Schema: Ensure the meta table exists and has the correct structure:

    php artisan schema:dump
    
  4. Event Debugging: Listen for MetaHasBeenAdded to trace meta changes:

    MetaHasBeenAdded::dispatch($meta, $model);
    

Extension Points

  1. Custom Meta Types: Extend the type system by adding to config/multiplex.php:

    'types' => [
        'custom_type' => \App\CustomType::class,
    ],
    
  2. Override Default Behavior: Publish and modify the package’s config:

    php artisan vendor:publish --provider="Kolossal\Multiplex\MultiplexServiceProvider"
    
  3. Add Query Scopes: Extend the Meta model:

    class Meta extends \Kolossal\Multiplex\Models\Meta
    {
        public function scopeActive($query)
        {
            return $query->where('published_at', '<=', now());
        }
    }
    
  4. Hook into Events: Register listeners in EventServiceProvider:

    protected $listen = [
        \Kolossal\Multiplex\Events\MetaHasBeenAdded::class => [
            \App\Listeners\LogMetaChange::class,
        ],
    ];
    

Configuration Quirks

  1. Default Meta Keys: Set default_meta_keys in config/multiplex.php to auto-include keys:

    'default_meta_keys' => ['likes', 'views', 'hidden'],
    
  2. Strict Mode: Enable strict_mode to throw exceptions for invalid keys:

    'strict_mode' => true,
    
  3. Fallback Behavior: Disable fallback to database columns by setting:

    'fallback_to_columns' => false,
    
  4. Time Handling: Customize the default time resolution (e.g., milliseconds) in config/multiplex.php:

    'time_resolution' => 'milliseconds',
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle