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

spatie/laravel-sluggable

Automatically generate unique slugs for Eloquent models on create/update. Supports collision suffixes, translatable slugs, and customizable slug options. Includes “self-healing” URLs that keep old links working via slug+id route keys and redirects.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Opinionated but flexible: The package aligns well with Laravel’s Eloquent ecosystem, leveraging attributes (PHP 8+) and traits for clean, declarative slug generation. The #[Sluggable] attribute reduces boilerplate for 90% of use cases, while the HasSlug trait provides granular control for edge cases (e.g., dynamic sources, conditional generation).
  • SEO/URL-first design: Self-healing URLs (slug + ID) mitigate broken links during updates, a critical feature for content-heavy applications (e.g., blogs, e-commerce). The 308 redirect (permanent) is semantically correct for canonical URLs.
  • Extensibility: Custom suffix generators, scoped uniqueness, and translatable slugs (via spatie/laravel-translatable) make it adaptable to multilingual or tenant-isolated systems.

Integration Feasibility

  • Low friction: Installation is a single composer require; migration is optional (slug column can be added post-install). The package auto-discovers models via attributes/traits.
  • Database agnostic: Works with any Laravel-supported database (MySQL, PostgreSQL, SQLite). No schema migrations required if using an existing slug column.
  • Route integration: Self-healing URLs require minimal route adjustments (e.g., {slug}-{id} instead of {slug}). Existing routes can coexist via conditional logic.

Technical Risk

  • Performance: Slug uniqueness checks add a query per save. For high-write workloads (e.g., 10K+ posts/hour), consider:
    • Disabling unique: true if duplicates are acceptable (e.g., internal tools).
    • Caching slug generation results (e.g., via Laravel’s cache).
    • Using extraScope() to limit uniqueness checks to relevant subsets (e.g., by tenant_id).
  • Backward compatibility: Self-healing URLs break existing routes unless migrated incrementally. Plan for:
    • Dual routes during transition (e.g., {slug}308 to {slug}-{id}).
    • URL rewrites for legacy links (e.g., via .htaccess or a middleware).
  • Edge cases:
    • Unicode/transliteration: The language option handles non-ASCII characters, but test with your app’s locales (e.g., Cyrillic, CJK).
    • Concurrent writes: Race conditions on slug generation are unlikely but possible. The package uses Laravel’s DB transactions to mitigate this.

Key Questions

  1. Use case priority:
    • Is SEO/URL stability (self-healing) a must-have, or is basic slug generation sufficient?
    • Are translatable slugs needed (requires spatie/laravel-translatable)?
  2. Performance constraints:
    • What’s the expected write volume for sluggable models? Can uniqueness checks be scoped?
  3. Migration strategy:
    • How will existing URLs (without IDs) be handled during the transition to self-healing?
  4. Customization needs:
    • Are there requirements for non-standard slug formats (e.g., UUIDs, hashed values)?
    • Will slugs need to be regenerated programmatically (e.g., via generateSlug())?

Integration Approach

Stack Fit

  • Laravel-native: Built for Laravel 10+ (PHP 8.1+), with zero framework overrides. Compatible with:
    • Eloquent models (attributes/traits).
    • Laravel’s routing system (self-healing URLs).
    • Spatie’s other packages (e.g., laravel-translatable for multilingual apps).
  • Tooling integration:
    • Laravel Boost: AI assistants (e.g., GitHub Copilot) can scaffold sluggable models automatically.
    • Laravel Pint: The package’s codebase adheres to Laravel’s PSR-12 standards.
  • Testing: Includes Pest tests; integrates with Laravel’s testing helpers (e.g., actingAs, assertRedirect).

Migration Path

  1. Assessment phase:
    • Audit existing models for slug usage (manual or custom logic).
    • Identify models needing slugs (e.g., Post, Product, Article).
  2. Pilot integration:
    • Start with non-critical models (e.g., internal tools) to test performance and edge cases.
    • Use the attribute syntax (#[Sluggable]) for 80% of cases; reserve the trait for complex logic.
  3. Incremental rollout:
    • Phase 1: Add slug columns to DB (if missing) and apply attributes/traits.
    • Phase 2: Update routes to support self-healing URLs (e.g., {slug}-{id}).
    • Phase 3: Implement redirects for legacy URLs (e.g., middleware to 308 old {slug} to {slug}-{id}).
  4. Validation:
    • Test slug generation for edge cases (e.g., special characters, empty titles).
    • Verify self-healing redirects work for both GET and POST routes.

Compatibility

  • Laravel versions: Officially supports Laravel 10+. For older versions, check the UPGRADING.md guide.
  • PHP versions: Requires PHP 8.1+ (for attributes). Test with your app’s PHP version.
  • Database: No vendor-specific SQL; works with all Laravel-supported databases.
  • Caching: Slug generation is not cached by default. For high-traffic apps, consider:
    • Caching the Str::slug() result in memory (e.g., Cache::remember).
    • Using a read replica for uniqueness checks (if DB load is a concern).

Sequencing

  1. Pre-requisites:
    • Ensure Laravel 10+ and PHP 8.1+ are in use.
    • Add a slug column to target tables (e.g., string(255)).
  2. Core integration:
    • Install the package: composer require spatie/laravel-sluggable.
    • Publish config (if customizing): php artisan vendor:publish --tag="sluggable-config".
  3. Model updates:
    • Add use Spatie\Sluggable\Attributes\Sluggable; and #[Sluggable] to models.
    • For advanced use cases, add use Spatie\Sluggable\HasSlug; and implement getSlugOptions().
  4. Route updates:
    • Update route definitions to use {slug}-{id} (e.g., Route::get('/posts/{slug}-{id}', ...)).
    • Add middleware to handle legacy redirects (e.g., 308 from {slug} to {slug}-{id}).
  5. Testing:
    • Write unit tests for slug generation (e.g., assertEquals('hello-world', $post->slug)).
    • Test route binding and self-healing redirects.

Operational Impact

Maintenance

  • Dependencies:
    • Single Composer package with no external services. Updates are straightforward (composer update).
    • No cron jobs or external APIs required.
  • Configuration:
    • Defaults are sensible; customization is optional (e.g., config/sluggable.php).
    • Translatable slugs require spatie/laravel-translatable (additional maintenance).
  • Monitoring:
    • Log slug generation failures (e.g., try-catch around generateSlug()).
    • Track self-healing redirect traffic to identify broken links.

Support

  • Troubleshooting:
    • Common issues: slug collisions, route binding failures, or self-healing redirects not triggering.
    • Debugging tools:
      • dd($model->getSlugOptions()) to inspect configuration.
      • php artisan route:list to verify route binding.
      • tail -f storage/logs/laravel.log for slug generation errors.
    • Community: Active GitHub issues (1.5K+ stars) and Spatie’s support channels.
  • Documentation:
    • Comprehensive docs with examples for attributes, traits, and advanced use cases.
    • Clear migration guides for upgrading between major versions.

Scaling

  • Performance:
    • Uniqueness checks: Each save adds a query to check for slug collisions. For high-throughput apps:
      • Use extraScope() to limit checks to relevant records (e.g., by tenant_id).
      • Consider disabling unique: true if duplicates are acceptable (e.g., internal dashboards).
    • Self-healing URLs: Redirects add minimal overhead (~1ms per request). Cache redirect responses if needed.
    • Database load: Test with your app’s expected concurrency (e.g., load test with laravel-shift/laravel-queues-testbench).
  • Horizontal scaling:
    • Stateless package; no shared state between instances.
    • Slug generation is idempotent (same input → same output).
  • Caching strategies:
    • Cache slug generation results in memory (e.g., `Cache::remember
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony