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.
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.
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();
}
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:
"?!?!") return "". Validate before using in URLs."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.
How can I help you explore Laravel packages today?