This package provides as trait that will generate a unique slug when saving model. The trait can be applied on any model.
$model = new EloquentModel();
$model->name = 'activerecord is awesome';
$model->save();
echo $model->url; //ouputs "activerecord-is-awesome"
The slug will be generated with Laravels str_slug
-method. Spaces will be converted to '-'.
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
You can install the package via composer:
$ composer require spatie/laravel-sluggable
The package provides a Spatie\Sluggable\HasSlug
-trait that can be applied on any Eloquent model.
The trait contains an abstract method getSlugOptions()
that you must implement yourself.
This is the most simple implementation:
use Spatie\Sluggable\Slug;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('url');
}
Want to use multiple field as the basis for a slug? No problem!
use Spatie\Sluggable\Slug
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom(['first_name', 'last_name'])
->saveSlugsTo('url');
}
By default the package will generate unique slugs by appending '-' and a number to a slug that already exists.
You can disable this behaviour by calling allowDuplicateSlugs
.
use Spatie\Sluggable\Slug
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('url')
->allowDuplicateSlugs();
}
You can also put a maximum size limit on the created slug.
use Spatie\Sluggable\Slug
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('url')
->slugsShouldBeNoLongerThan(50);
}
The slug can be slightly longer that the value specified as the suffix to make it unique is added.
Please see CHANGELOG for more information what has changed recently.
$ composer test
Please see CONTRIBUTING for details.
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
The MIT License (MIT). Please see License File for more information.