josezenem/laravel-slugidable

A package for Laravel that creates slugs for Eloquent models based on title and ID

Fund package maintenance!
josezenem

1.2.0 2024-03-12 21:38 UTC

README

Latest Stable Version Tests Total Downloads

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.

Installation

You can install the package via composer:

composer require josezenem/laravel-slugidable

Usage

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.

Configuration

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

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.