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

Slugify Laravel Package

cocur/slugify

cocur/slugify converts strings into URL-friendly slugs by stripping special characters and transliterating many languages (e.g., ä → ae). Lightweight with no external dependencies, PSR-4, PHP 8.0–8.5, and integrations for Laravel, Symfony, Twig, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer: composer require cocur/slugify. Start by instantiating the base Slugify class and calling slugify():

use Cocur\Slugify\Slugify;

$slugify = new Slugify();
echo $slugify->slugify('Hello World!'); // "hello-world"
echo $slugify->slugify('Café & Bistro'); // "cafe-bistro"

For multilingual content (e.g., Cyrillic, Arabic), transliteration works out of the box—no extra setup needed. Begin with simple use cases: generating slugs for blog posts, product URLs, or route keys. Check the README.md and examples/ in the repo for quick validation patterns.

Implementation Patterns

  • Laravel Integration: Create a service provider or macro. Example macro for Eloquent models:

    // In a service provider
    Str::macro('slug', function ($string, $divider = '-') {
        static $slugify;
        $slugify = $slugify ?: new \Cocur\Slugify\Slugify(['regexp' => '/[^a-z0-9]+/i', 'separator' => $divider]);
        return $slugify->slugify($string);
    });
    

    Use via Str::slug('My New Post', '-').

  • Per-Model Customization: Extend your model with a slugify() helper method:

    public function getSlugAttribute()
    {
        return app(Slugify::class)->slugify($this->title);
    }
    
  • Custom Rules for Exceptions: Define rule providers for domain-specific needs (e.g., turning “C#” → “c-sharp”):

    $slugify->addRule('#', 'sharp');
    $slugify->slugify('C# Programming'); // "c-sharp-programming"
    
  • Bulk Processing: Integrate into data importers or seeding to normalize existing datasets:

    foreach ($products as $product) {
        $product->slug = $slugify->slugify($product->name);
        $product->save();
    }
    

Gotchas and Tips

  • Separator Consistency: Ensure your separator (-, _, or none) is uniform across your app. Default is -, but override via constructor: new Slugify(['separator' => '_']).

  • Performance Pitfalls: Avoid re-instantiating Slugify on every call. Use DI (e.g., bind as singleton in Laravel) or static caching. Profiling shows ~10–100x faster with reuse on 1k+ calls.

  • Edge Cases:

    • Strings with only special chars (e.g., "?!?!") return "". Validate before using in URLs.
    • Multiple separators collapse (e.g., "a---b""a-b"), which is usually desired—but verify if needed.
  • Extensibility: For complex linguistic needs (e.g., German ß → “ss”, Danish æ → “ae”), use built-in providers or contribute to the rules/ directory. Example: add a custom provider with addProvider(new MyProvider()).

  • Configuration Overriding: You can change behavior at runtime with configure():

    $slugify->configure(['lowercase' => false]);
    echo $slugify->slugify('Hello World'); // "Hello-World"
    
  • Debugging: Enable DEBUG constant temporarily (or wrap calls with error_log()) if transliteration seems off. Missing locale data? Ensure ext-intl is installed—Slugify falls back to iconv if missing, which may yield inconsistent results.

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport