Top Related Projects
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.
A Laravel package for multilingual models
A Hashids bridge for Laravel
Quick Overview
Laravel-sluggable is a package for Laravel that provides an easy way to create slugs for your Eloquent models. It automatically generates URL-friendly slugs based on one or more attributes of your model, ensuring uniqueness and customization options.
Pros
- Easy integration with Laravel Eloquent models
- Customizable slug generation with multiple source fields
- Automatic handling of slug uniqueness
- Supports translatable slugs for multilingual applications
Cons
- Limited to Laravel framework
- May require additional configuration for complex slug generation scenarios
- Potential performance impact on large datasets when checking for uniqueness
- Might conflict with other packages that modify Eloquent model behavior
Code Examples
- Basic usage with a single source field:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Post extends Model
{
use HasSlug;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
}
- Using multiple source fields for slug generation:
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom(['title', 'subtitle'])
->saveSlugsTo('slug');
}
- Customizing slug generation with a callback:
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug')
->slugsShouldBeNoLongerThan(50)
->usingSeparator('_')
->usingLanguage('nl')
->withCustomSlugGenerator(function(string $string): string {
return strtoupper($string);
});
}
Getting Started
-
Install the package via Composer:
composer require spatie/laravel-sluggable -
Add the
HasSlugtrait to your Eloquent model and implement thegetSlugOptions()method:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class YourModel extends Model
{
use HasSlug;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
}
- Use the model as usual, and the slug will be automatically generated and saved when the model is created or updated.
Competitor Comparisons
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.
Pros of Slugify
- Framework-agnostic, can be used in any PHP project
- Supports a wide range of languages and special characters
- Highly customizable with options for custom rules and translations
Cons of Slugify
- Requires manual integration with Laravel models
- Lacks built-in features for handling duplicate slugs in a database context
Code Comparison
Slugify:
use Cocur\Slugify\Slugify;
$slugify = new Slugify();
$slug = $slugify->slugify('Hello World!');
Laravel-sluggable:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Post extends Model
{
use HasSlug;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
}
Key Differences
- Laravel-sluggable is specifically designed for Laravel, offering seamless integration with Eloquent models
- Slugify provides more flexibility for use in various PHP projects but requires more manual setup in Laravel
- Laravel-sluggable handles duplicate slugs automatically, while Slugify requires custom implementation
- Slugify offers more extensive language support out of the box
Both libraries are well-maintained and popular choices for slug generation in PHP projects, with the choice depending on the specific requirements of your project and whether you're working within the Laravel framework.
A Laravel package for multilingual models
Pros of laravel-translatable
- Supports multiple languages and translations for model attributes
- Offers flexible translation storage options (JSON, separate tables)
- Provides scopes for querying translated models efficiently
Cons of laravel-translatable
- More complex setup and configuration compared to laravel-sluggable
- Potentially higher database overhead due to additional translation tables
- May require more careful handling of fallback languages and translations
Code Comparison
laravel-translatable:
use Astrotomic\Translatable\Translatable;
class Post extends Model
{
use Translatable;
public $translatedAttributes = ['title', 'content'];
}
laravel-sluggable:
use Spatie\Sluggable\HasSlug;
class Post extends Model
{
use HasSlug;
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()->generateSlugsFrom('title');
}
}
While laravel-translatable focuses on multilingual content management, laravel-sluggable specializes in generating URL-friendly slugs. laravel-translatable offers more comprehensive internationalization features but requires additional setup. laravel-sluggable provides a simpler solution for creating slugs from model attributes, making it more suitable for projects that don't require extensive multilingual support.
A Hashids bridge for Laravel
Pros of laravel-hashids
- Provides unique, non-sequential identifiers for database records
- Offers better security by obfuscating actual database IDs
- Allows for easy decoding of hashids back to original IDs
Cons of laravel-hashids
- Requires additional setup and configuration
- May increase complexity in URL structure and database queries
- Not suitable for SEO-friendly URLs like slugs
Code Comparison
laravel-hashids:
use Vinkla\Hashids\Facades\Hashids;
$id = 1;
$hashid = Hashids::encode($id);
$decodedId = Hashids::decode($hashid)[0];
laravel-sluggable:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
While laravel-hashids focuses on generating unique, encoded identifiers for database records, laravel-sluggable is designed to create SEO-friendly URL slugs based on model attributes. laravel-hashids offers better security and obfuscation of IDs, but laravel-sluggable provides more natural, readable URLs. The choice between the two depends on the specific requirements of your project, such as security needs, URL structure preferences, and SEO considerations.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
This package generates a unique slug for any Eloquent model whenever it is created or updated. Add a #[Sluggable] attribute to the model and the package handles the rest.
use Spatie\Sluggable\Attributes\Sluggable;
#[Sluggable(from: 'title', to: 'slug')]
class Post extends Model
{
}
$post = Post::create(['title' => 'activerecord is awesome']);
$post->slug; // "activerecord-is-awesome"
For features that need closures (custom source callables, scoped uniqueness, conditional skip, custom suffix generators) use the HasSlug trait with a getSlugOptions() method instead.
Highlights
- Unique slugs out of the box, with a configurable
-1,-2, ... suffix on collisions. - Self-healing URLs: route keys that combine the slug with the primary key (
hello-world-5) so renaming a model never breaks an existing link. Stale slugs return a308redirect to the canonical URL. - Translatable slugs through
HasTranslatableSlugandspatie/laravel-translatable. - Overridable actions: swap the slug generator or the self-healing URL logic for your own class via a config file.
- Laravel Boost skill bundled with the package, so AI assistants know how to scaffold sluggable models in your project. Boost discovers it automatically once both packages are installed.
Self-healing URLs combine the slug with the primary key. The HasSlug trait is required alongside the attribute, because it overrides Eloquent's route key and route binding methods.
#[Sluggable(from: 'title', to: 'slug', selfHealing: true)]
class Post extends Model
{
use HasSlug;
}
// /posts/hello-world-5 â 200
// /posts/old-title-5 â 308 to /posts/hello-world-5
Spatie is a web design agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Documentation
All documentation is available on our documentation site.
Installation
composer require spatie/laravel-sluggable
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
Top Related Projects
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.
A Laravel package for multilingual models
A Hashids bridge for Laravel
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot
