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

novius/laravel-meta

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require novius/laravel-meta
    
  2. Add the addMeta() macro to your migration:
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('text');
        $table->timestamps();
        $table->addMeta(); // Adds meta table and foreign key
    });
    
  3. Use the HasMeta trait in your model:
    use Novius\LaravelMeta\Traits\HasMeta;
    
    class Post extends Model {
        use HasMeta;
    }
    
  4. Access metadata:
    $post = Post::first();
    $post->setMeta(['custom_field' => 'value']);
    $post->meta->custom_field; // Access via relationship
    

First Use Case: SEO Management

For a blog post model, leverage the built-in SEO fields:

$post->seo_title = 'Optimized Title';
$post->seo_description = 'Meta description for SEO';
$post->canBeIndexedByRobots(); // Set robots meta

Implementation Patterns

Core Workflows

  1. Model Integration:

    • Apply HasMeta trait to any Eloquent model.
    • Override getMetaConfig() for custom defaults (e.g., fallback titles, image paths).
  2. Metadata Operations:

    • Set/Get: $model->setMeta(['key' => 'value']) or $model->meta->key = 'value'.
    • Bulk Update: Use updateMeta() for mass assignments.
    • Validation: Extend with setMetaRules() for custom validation logic.
  3. Querying:

    • Scopes: $model::indexableByRobots() or $model::whereMeta('key', 'value') (via raw queries if needed).
    • Eager Loading: $model->with('meta') to avoid N+1 queries.
  4. Frontend Integration:

    • Use the CurrentModel facade to pass metadata to views:
      CurrentModel::setModel($post);
      @include('laravel-meta::meta') // Renders SEO/OpenGraph tags
      

Integration Tips

  • Nova/Filament:

    • Use NovaResourceHasMeta or FilamentResourceHasMeta traits to auto-generate admin panels for metadata fields.
    • Customize fields via getSEONovaFields() or getFormSEOFields().
  • Events:

    • Listen to meta.saving or meta.saved events for pre/post-processing:
      $model->meta->save(function ($meta) {
          $meta->normalizeKeys(); // Example custom logic
      });
      
  • Testing:

    • Mock HasMeta trait in unit tests:
      $model = new class extends Model {
          use HasMeta;
      };
      

Gotchas and Tips

Pitfalls

  1. Performance:

    • JSON Column: Default addMeta() uses a JSON column, which can bloat storage and slow queries. For high-traffic models, consider a dedicated meta table with normalized columns.
    • Query Overhead: Avoid complex queries on metadata (e.g., whereJsonContains) unless indexed. Use raw SQL or scopes for performance-critical paths.
  2. Configuration:

    • Missing getMetaConfig(): If not defined, the trait uses defaults, which may not suit all use cases (e.g., fallbackTitle).
    • Disk/Path Mismatches: Incorrect ogImageDisk or ogImagePath in getMetaConfig() will break image URL generation.
  3. AGPL License:

    • Compliance: Ensure your project’s license aligns with AGPL-3.0. Contributions back to the package may be required if modifications are made.
  4. Migration Risks:

    • Retrofitting: Adding addMeta() to an existing table requires downtime or a zero-downtime strategy (e.g., adding a new column first).

Debugging Tips

  • Missing Metadata:

    • Verify the meta table exists and the foreign key is set up correctly.
    • Check for errors in getMetaConfig() (e.g., undefined callbacks).
  • SEO Tag Issues:

    • Use php artisan tinker to inspect metadata:
      $post->meta->toArray(); // Check raw data
      
    • Validate OpenGraph image paths with:
      $post->og_image_url; // Should return a valid URL
      
  • Query Problems:

    • For slow queries, use Laravel Debugbar or DB::enableQueryLog() to identify bottlenecks.

Extension Points

  1. Custom Metadata Types:

    • Extend the trait to support non-string metadata (e.g., arrays, objects) via casts or accessors.
  2. Validation:

    • Add rules to setMetaRules():
      public function setMetaRules(): array {
          return [
              'seo_keywords' => 'required|string|max:255',
          ];
      }
      
  3. Query Builder:

    • Add custom scopes to the trait:
      public function scopePublished($query) {
          return $query->whereMeta('status', 'published');
      }
      
  4. Caching:

    • Cache metadata for read-heavy workloads:
      $meta = Cache::remember("meta_{$model->id}", 60, function () use ($model) {
          return $model->meta;
      });
      
  5. Multi-Tenancy:

    • Override the trait to scope metadata by tenant:
      public function getMetaTable() {
          return 'tenant_' . tenant()->id . '_' . parent::getMetaTable();
      }
      
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky