A package for Laravel that creates slugs for Eloquent models based on both a title and ID
$model = new Blog();
$model->title = 'Dwight jumped over the fence';
$model->save();
echo $model->slug; // output: dwight-jumped-over-the-fence-012422
All settings are fully configurable for each model.
You can install the package via composer:
composer require josezenem/laravel-slugidable
Simply Josezenem\Slugidable\Slugidable
trait to your model.
// App\Models\Blog
<?php
use Josezenem\Slugidable\Slugidable;
class Blog extends Model {
use Slugidable;
protected $fillable = [
'title',
'slug',
];
}
$blog = create([
'title' => 'My dog Dwight jumped over the fence',
])
// When this is created, it will make the slug of
//my-dog-dwight-jumped-over-the-fence-1
We have included a handy scope method: fromSlugidable() that will extract the ID from the slug and search the model
$blog = Blog::fromSlugidable('my-dog-dwight-012422')->first();
// in this scenario only ID: 012422 is used inside the scope to find the slug.
By default we use id, title, slug columns from the model, but you can override these settings by adding the following method to your model.
protected function configureSlugidableSettings():void
{
$this->slugidableSettings = [
'slug_from' => 'title',
'slug_to' => 'slug',
'using_key_name' => $this->getKeyName(),
'on' => 'suffix',
'using_separator' => '-',
'force_slug_from' => false,
];
}
- slug_from is where the slug will grab the the slug from
- slug_to the place where the slug lives
- using_key_name the ID field used to prefix or suffix the ID
- on could be "prefix" to have the ID before the slug text, or "suffix" to have it after.
- using_separator the seperator to use during slug creation
- force_slug_from force the system to always slug from 'slug_from' regardless if
slug_to
is present
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.