Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model.
bpocallaghan/sluggable is a Laravel package for provides a hasslug trait that will generate a unique slug when saving your laravel eloquent model..
It currently has 6 GitHub stars and 23.937 downloads on Packagist (latest version 1.6.1).
Install it with composer require bpocallaghan/sluggable.
Discover more Laravel packages by bpocallaghan
or browse all Laravel packages to compare alternatives.
Last updated
Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model.
The slugs are generated with Laravel str_slug method, whereby spaces are converted to '-'.
$model = new EloquentModel();
$model->name = 'laravel is awesome';
$model->save();
echo $model->slug; // outputs "laravel-is-awesome"
Update your project's composer.json file.
composer require bpocallaghan/sluggable
Your Eloquent models can use the Bpocallaghan\Sluggable\HasSlug trait and the Bpocallaghan\Sluggable\SlugOptions class.
The trait has a protected method getSlugOptions() that you can implement for customization.
Here's an example:
class YourEloquentModel extends Model
{
use HasSlug;
/**
* This function is optional and only required
* when you want to override the default behaviour
*/
protected function getSlugOptions()
{
return SlugOptions::create()
->slugSeperator('-')
->generateSlugFrom('name')
->saveSlugTo('slug');
}
}
If you want to generate your slug from a relationship.
class YourEloquentModel extends Model
{
use HasSlug;
public function getNameAndFooAttribute()
{
$name = $this->name;
if ($this->foo) {
$name .= " {$this->foo->name}";
}
return $name;
}
protected function getSlugOptions()
{
return SlugOptions::create()
->generateSlugFrom('name_and_foo');
}
}
You do not have to add the method in you model (the above will be used as default).
It is only needed when you want to change the default behaviour.
By default it will generate a slug from the name and save to the slug column.
It will suffix a -1 to make the slug unique. You can disable it by calling makeSlugUnique(false).
It will use the - as a separator. You can change this by calling slugSeperator('_').
You can use multiple fields as the source of the slug generateSlugFrom(['firstname', 'lastname']).
You can also pass a callable function to generateSlugFrom().
Have a look here for the options and available config functions.