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

oleaass/laravel-sluggable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Run composer require oleaass/laravel-sluggable in your project root.
  2. Model Integration: Add the Sluggable trait to your Eloquent model (e.g., Post).
  3. Configure Slug Source: Define getSlugOptions() in your model to specify the slug source (e.g., title).

First Use Case

Generate a slug for a new Post model:

$post = Post::create(['title' => 'Hello World']);
echo $post->slug; // Output: hello-world

Where to Look First

  • Model Configuration: Focus on getSlugOptions() to customize slug behavior.
  • Database Migration: Ensure your table has a slug column (default) or specify a custom column via dest option.
  • Validation: Check if allowDuplicate is false (default) to enforce uniqueness.

Implementation Patterns

Common Workflows

  1. Basic Slug Generation

    // Auto-generate slug on create (default)
    $post = Post::create(['title' => 'Laravel Sluggable']);
    
  2. Manual Slug Override

    // Skip auto-generation and set slug manually
    $post = Post::create([
        'title' => 'Custom Slug Post',
        'slug'  => 'custom-slug-overridden'
    ]);
    
  3. Dynamic Slug Sources

    // Use multiple fields (e.g., title + category)
    public function getSlugOptions(): array {
        return [
            'source' => function () {
                return strtolower($this->title . '-' . $this->category->name);
            }
        ];
    }
    
  4. Update Behavior

    // Update slug on title change (requires `onUpdate: true`)
    $post->update(['title' => 'Updated Title']);
    echo $post->fresh()->slug; // Updated slug
    

Integration Tips

  • Form Requests: Validate slug uniqueness before saving:
    public function rules() {
        return [
            'slug' => 'required|unique:posts,slug,' . $this->post->id,
        ];
    }
    
  • API Resources: Expose slug in JSON responses:
    public function toArray($request) {
        return [
            'slug' => $this->slug,
            // ...
        ];
    }
    
  • SEO URLs: Use slugs in routes:
    Route::get('/posts/{slug}', [PostController::class, 'show']);
    

Gotchas and Tips

Pitfalls

  1. Duplicate Slugs

    • Issue: If allowDuplicate: true, slugs may collide.
    • Fix: Set allowDuplicate: false (default) and handle conflicts in getSlugOptions:
      'source' => function () {
          $slug = Str::slug($this->title);
          return Post::where('slug', $slug)->exists() ? $slug . '-1' : $slug;
      }
      
  2. Case Sensitivity

    • Issue: Database collations may treat Slug and slug as different.
    • Fix: Normalize case in getSlugOptions:
      'source' => function () {
          return Str::lower(Str::slug($this->title));
      }
      
  3. Performance on Update

    • Issue: Updating slugs on every save() can slow down bulk operations.
    • Fix: Disable auto-update for non-critical fields:
      public function getSlugOptions(): array {
          return [
              'onUpdate' => false, // Disable slug updates
          ];
      }
      
  4. Reserved Words

    • Issue: Slugs like create or update may conflict with Laravel methods.
    • Fix: Use a custom dest column (e.g., url_slug).

Debugging

  • Check Slug Generation: Temporarily log the slug source:
    public function getSlugOptions(): array {
        \Log::debug('Slug source:', ['source' => $this->title]);
        return ['source' => 'title'];
    }
    
  • Verify Database: Ensure the slug column exists and matches the dest option.

Extension Points

  1. Custom Slug Logic Override the generateSlug method in your model:

    public function generateSlug(): string {
        return parent::generateSlug() . '-custom';
    }
    
  2. Event Listeners Trigger events for slug changes:

    protected static function booted() {
        static::saved(function ($model) {
            if ($model->wasChanged('slug')) {
                event(new SlugUpdated($model));
            }
        });
    }
    
  3. Testing Mock slug generation in tests:

    $post = Post::create(['title' => 'Test']);
    $this->assertEquals('test', $post->slug);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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