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 Meta Laravel Package

kodeine/laravel-meta

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kodeine/laravel-meta
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Kodeine\Meta\MetaServiceProvider"
    
  2. Apply the Trait: Use the Metable trait in your Eloquent model:

    use Kodeine\Meta\Traits\Metable;
    
    class Post extends Model
    {
        use Metable;
    }
    
  3. First Use Case: Access or modify metadata fluently:

    $post = Post::find(1);
    $post->meta('author_name', 'John Doe'); // Set meta
    $post->meta('author_name');             // Get meta (returns 'John Doe')
    $post->meta('author_name', null);       // Unset meta
    
  4. Configuration: Check config/meta.php for default settings (e.g., meta_column, meta_prefix).


Implementation Patterns

Core Workflows

  1. CRUD Operations:

    // Set multiple meta keys at once
    $post->meta(['author_name' => 'Jane Smith', 'tags' => ['laravel', 'meta']]);
    
    // Check if meta exists
    if ($post->meta('author_name')) {
        // ...
    }
    
    // Delete a single meta key
    $post->meta('author_name', null);
    
    // Clear all meta data
    $post->clearMeta();
    
  2. Integration with Eloquent Events: Use saving, saved, etc., to sync meta data:

    $post->saving(function ($model) {
        $model->meta('updated_at', now());
    });
    
  3. Query Scopes: Filter models by meta data:

    // Find posts with a specific meta key
    $posts = Post::whereMeta('author_name', 'John Doe')->get();
    
    // Find posts with meta containing a value
    $posts = Post::whereMetaContains('tags', 'laravel')->get();
    
  4. Caching Meta Data: Cache meta data for performance (e.g., using Laravel's cache):

    $post->meta('cached_value', Cache::get('key'), true); // Cache on set
    
  5. Serialization: Automatically serialize/deserialize meta values (e.g., arrays):

    $post->meta('tags', ['laravel', 'meta']); // Automatically serialized
    $post->meta('tags'); // Returns ['laravel', 'meta']
    
  6. Model Casting: Cast meta values to custom types (e.g., Carbon instances):

    protected $casts = [
        'meta.published_at' => 'datetime',
    ];
    

Gotchas and Tips

Common Pitfalls

  1. Column Name Conflicts:

    • Ensure meta_column in config doesn’t conflict with existing columns.
    • Default: meta_data (stores JSON-encoded meta key-value pairs).
  2. Serialization Issues:

    • Non-serializable values (e.g., closures, resources) will throw errors.
    • Fix: Explicitly cast or handle serialization in meta() calls.
  3. Mass Assignment Risks:

    • Meta data is not protected by default. Use $guarded or $fillable:
      protected $guarded = ['meta.*']; // Block mass assignment for meta
      
  4. Performance with Large Meta Data:

    • Avoid storing large binary data (e.g., files) in meta.
    • Tip: Use whereMeta sparingly on large datasets; add database indexes to meta_column.
  5. Laravel 8+ Quirks:

    • If using Laravel 8+, ensure useHashedIds() or other model behaviors don’t interfere with meta queries.
  6. Testing Meta Data:

    • Reset meta data in tests:
      $post->clearMeta();
      $post->save();
      

Debugging Tips

  1. Inspect Raw Meta Data:

    dd($post->getMeta()); // Raw array of all meta data
    
  2. Check Database Storage:

    SELECT meta_data FROM posts WHERE id = 1;
    
    • Verify JSON structure matches expectations.
  3. Enable Query Logging:

    \DB::enableQueryLog();
    $posts = Post::whereMeta('key', 'value')->get();
    dd(\DB::getQueryLog());
    

Extension Points

  1. Custom Meta Storage: Override getMetaSource() to use a different storage backend (e.g., Redis):

    public function getMetaSource()
    {
        return Cache::store('redis');
    }
    
  2. Meta Events: Listen for meta changes via events:

    event(new MetaUpdated($post, 'author_name', 'John Doe'));
    
  3. Dynamic Meta Accessors: Use meta() with dynamic keys:

    $key = 'dynamic_' . $id;
    $post->meta($key, 'value');
    
  4. Meta Validation: Validate meta data in boot():

    static::saving(function ($model) {
        if ($model->meta('price') && $model->meta('price') < 0) {
            throw new \Exception('Price cannot be negative');
        }
    });
    
  5. Fallback Values: Provide defaults in meta():

    $author = $post->meta('author_name', 'Anonymous');
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle