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

oleaass/laravel-tags

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require oleaass/laravel-tags
    php artisan migrate
    
    • Runs migrations for tags and taggables tables.
  2. Enable Tagging on a Model: Add the Taggable trait to your Eloquent model:

    use OleAass\Tags\Taggable;
    
    class Post extends Model
    {
        use Taggable;
    }
    
    • This automatically adds a tags() relationship method.
  3. First Use Case:

    // Create a model
    $post = Post::create(['title' => 'Hello World']);
    
    // Create a tag (optional: use existing via `Tag::findOrCreate()`)
    $tag = \OleAass\Tags\Models\Tag::create(['name' => 'laravel']);
    
    // Attach the tag to the model
    $post->tags()->attach($tag->id);
    

Where to Look First

  • Migrations: Check database/migrations/ for tags and taggables tables.
  • Tag Model: \OleAass\Tags\Models\Tag for tag-specific logic.
  • Taggable Trait: \OleAass\Tags\Taggable for model integration.

Implementation Patterns

Common Workflows

  1. Tagging a Model:

    // Attach existing tags
    $post->tags()->attach([1, 2, 3]);
    
    // Detach tags
    $post->tags()->detach([1]);
    
    // Sync tags (replace all)
    $post->tags()->sync([1, 2]);
    
  2. Creating Tags on the Fly:

    // Create and attach a tag in one step
    $post->tags()->attach(
        \OleAass\Tags\Models\Tag::firstOrCreate(['name' => 'php'])->id
    );
    
  3. Querying Tagged Models:

    // Find posts with a specific tag
    $posts = Post::whereHas('tags', function($query) {
        $query->where('name', 'laravel');
    })->get();
    
  4. Pivot Data: Use the taggables table to store extra metadata (e.g., created_at):

    $post->tags()->attach($tag->id, ['created_at' => now()]);
    

Integration Tips

  • Validation: Validate tag names before creation (e.g., slugify or trim).
  • Scopes: Add custom scopes to your model for common tag queries:
    public function scopeWithTag($query, $tagName) {
        return $query->whereHas('tags', function($q) use ($tagName) {
            $q->where('name', $tagName);
        });
    }
    
  • Events: Listen for tagged or detached events via Laravel events:
    $post->tags()->attach($tag->id);
    // Dispatches: \OleAass\Tags\Events\Tagged
    

Gotchas and Tips

Pitfalls

  1. Duplicate Tags:

    • The package doesn’t enforce uniqueness by default. Use firstOrCreate or validate manually:
      $tag = \OleAass\Tags\Models\Tag::firstOrCreate(['name' => strtolower(trim($name))]);
      
  2. Performance with Large Datasets:

    • whereHas queries can be slow. Use join for better performance:
      $posts = Post::join('taggables', 'posts.id', '=', 'taggables.taggable_id')
          ->join('tags', 'taggables.tag_id', '=', 'tags.id')
          ->where('tags.name', 'laravel')
          ->select('posts.*')
          ->get();
      
  3. Missing taggable_type:

    • The taggables table uses polymorphic relations. Ensure your model’s fully qualified class name (e.g., App\Models\Post) matches the taggable_type column.
  4. Caching:

    • Tag relationships aren’t cached by default. Use Laravel’s cache for frequent queries:
      $tags = Cache::remember("post:{$post->id}:tags", now()->addHours(1), function() use ($post) {
          return $post->tags;
      });
      

Debugging

  • Check Migrations: Run php artisan migrate:status to verify tables exist. Rollback with php artisan migrate:rollback if needed.

  • Pivot Data Issues: If attaching fails, inspect the taggables table for duplicate entries or malformed data.

  • Relationship Errors: Ensure the Taggable trait is used before defining relationships in your model.

Extension Points

  1. Custom Tag Model: Extend \OleAass\Tags\Models\Tag to add fields (e.g., color):

    class Tag extends \OleAass\Tags\Models\Tag {
        protected $fillable = ['name', 'color'];
    }
    
  2. Custom Pivot Model: Replace the default pivot table behavior by publishing and modifying the migration:

    php artisan vendor:publish --tag=tags-migrations
    

    Then extend the taggables table schema.

  3. Tagging Logic: Override the tags() relationship in your model:

    public function tags() {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }
    
  4. Tag Creation: Add a helper method to your model for common tagging:

    public function addTag($name) {
        return $this->tags()->attach(
            \OleAass\Tags\Models\Tag::firstOrCreate(['name' => $name])->id
        );
    }
    

Config Quirks

  • No Config File: The package uses default settings. For customization (e.g., table names), publish the config:

    php artisan vendor:publish --tag=tags-config
    

    Then modify config/tags.php.

  • Soft Deletes: Enable soft deletes for tags by adding SoftDeletes to the Tag model and updating migrations:

    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Tag extends Model {
        use SoftDeletes, \OleAass\Tags\Taggable;
    }
    
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.
besmartand-pro/php-quality-config
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