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

Eloquence Metable Laravel Package

sofa/eloquence-metable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sofa/eloquence-metable
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Sofa\Eloquence\Metable\MetableServiceProvider::class,
    ],
    
  2. Basic Usage Apply the Metable trait to your Eloquent model:

    use Sofa\Eloquence\Metable\Metable;
    
    class Product extends Model
    {
        use Metable;
    }
    
  3. First Use Case: Storing/Retrieving Metadata

    // Set metadata
    $product = new Product();
    $product->setMeta(['color' => 'red', 'price_range' => 'premium']);
    $product->save();
    
    // Retrieve metadata
    $metadata = $product->getMeta(); // ['color' => 'red', 'price_range' => 'premium']
    $color = $product->getMeta('color'); // 'red'
    

Implementation Patterns

1. Structured Metadata Management

  • Use Case: Store dynamic key-value pairs (e.g., product variants, user preferences).
  • Pattern:
    // Set nested metadata
    $product->setMeta(['specs' => ['weight' => '1kg', 'dimensions' => '10x20x30']]);
    
    // Retrieve nested metadata
    $weight = $product->getMeta('specs.weight'); // '1kg'
    

2. Integration with API Responses

  • Use Case: Expose metadata in API responses without bloating the model.
  • Pattern:
    // In a resource
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'meta' => $this->getMeta(), // Include metadata in response
        ];
    }
    

3. Conditional Metadata Handling

  • Use Case: Apply metadata logic based on business rules.
  • Pattern:
    // Set metadata conditionally
    if ($product->isPremium()) {
        $product->setMeta('price_range', 'premium');
    }
    
    // Check metadata existence
    if ($product->hasMeta('color')) {
        $color = $product->getMeta('color');
    }
    

4. Bulk Metadata Updates

  • Use Case: Update metadata for multiple records (e.g., batch processing).
  • Pattern:
    Product::where('category', 'electronics')->updateMeta([
        'stock_status' => 'in_stock',
        'last_updated' => now(),
    ]);
    

5. Serialization/Deserialization

  • Use Case: Store metadata as JSON or a custom format.
  • Pattern:
    // Override serialization (if needed)
    protected function serializeMeta($value)
    {
        return json_encode($value);
    }
    
    protected function deserializeMeta($value)
    {
        return json_decode($value, true);
    }
    

Gotchas and Tips

Pitfalls

  1. Database Column Mismatch

    • The package expects a meta column (e.g., JSON or TEXT type). Ensure your migration includes:
      $table->json('meta')->nullable(); // For Laravel 8+
      // OR
      $table->text('meta')->nullable();
      
  2. Nested Metadata Serialization

    • If using TEXT instead of JSON, nested arrays may not serialize/deserialize correctly. Prefer JSON for complex structures.
  3. Mass Assignment Risks

    • Metadata is not guarded by default. Explicitly whitelist safe keys:
      protected $metaFillable = ['color', 'price_range'];
      
  4. Performance with Large Metadata

    • Avoid storing excessively large metadata (e.g., entire documents). Use relationships for complex data.

Debugging Tips

  • Check Serialization: If metadata appears corrupted, verify serializeMeta/deserializeMeta methods or database column type.
  • Log Raw Data:
    \Log::debug('Raw meta:', [$product->meta]);
    
  • Validate JSON: Ensure metadata is valid JSON if using JSON column type.

Extension Points

  1. Custom Serialization Override serializeMeta/deserializeMeta for custom formats (e.g., YAML, XML).

  2. Meta Events Listen for metable.saving/metable.saved events to hook into metadata changes:

    event(new MetableSaving($model, $meta));
    
  3. Query Scopes Add custom scopes for metadata filtering:

    public function scopeWithMeta($query, $key, $value)
    {
        return $query->whereJsonContains('meta->>' . $key, $value);
    }
    
  4. Caching Metadata Cache frequently accessed metadata to reduce database reads:

    $meta = Cache::remember("meta_{$product->id}", now()->addHours(1), function () use ($product) {
        return $product->getMeta();
    });
    

Config Quirks

  • Default Column Name: Change the default meta column name via config:
    'metable' => [
        'column' => 'attributes', // Custom column name
    ],
    
  • Auto-Save: Disable auto-saving metadata on model save (if managing manually):
    protected $autoSaveMeta = false;
    
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