Wallogit.com
2017 © Pedro Peláez
Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model.
Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model., (*1)
The slugs are generated with Laravel str_slug method, whereby spaces are converted to '-'., (*2)
$model = new EloquentModel(); $model->name = 'laravel is awesome'; $model->save(); echo $model->slug; // ouputs "laravel-is-awesome"
Update your project's composer.json file., (*3)
composer require bpocallaghan/sluggable
Your Eloquent models can use the Bpocallaghan\Sluggable\HasSlug trait and the Bpocallaghan\Sluggable\SlugOptions class., (*4)
The trait has a protected method getSlugOptions() that you can implement for customization., (*5)
Here's an example:, (*6)
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., (*7)
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)., (*8)
It is only needed when you want to change the default behaviour., (*9)
By default it will generate a slug from the name and save to the slug column., (*10)
It will suffix a -1 to make the slug unique. You can disable it by calling makeSlugUnique(false)., (*11)
It will use the - as a separator. You can change this by calling slugSeperator('_')., (*12)
You can use multiple fields as the source of the slug generateSlugFrom(['firstname', 'lastname'])., (*13)
You can also pass a callable function to generateSlugFrom()., (*14)
Have a look here for the options and available config functions., (*15)
Please see the CHANGELOG for more information what has changed recently., (*16)
See it in action at a Laravel Admin Starter project., (*17)