A simple but beautiful unique slug generator for Laravel eloquent model.
composer require maniruzzaman/laravel-unique-slug
Service Provider Registration
In config/app.php
, add in providers
array -
'providers' => [
// ...
Akash\LaravelUniqueSlug\UniqueSlugServiceProvider::class,
// ...
],
Facade Class Alias Add in aliases array -
'aliases' => Facade::defaultAliases()->merge([
// ...
'UniqueSlug' => Akash\LaravelUniqueSlug\Facades\UniqueSlug::class,
// ...
])->toArray(),
use Akash\LaravelUniqueSlug\Facades\UniqueSlug;
Let's assume, we have in Post
class, we've added slug
column which is unique. Now, if we passed title
and generate slug
from that, then -
use App\Models\Post;
// First time create post with title Simple Post
UniqueSlug::generate(Post::class, 'Simple Post', 'slug');
// Output: simple-post
// Second time create post with title Simple Post
UniqueSlug::generate(Post::class, 'Simple Post', 'slug');
// Output: simple-post-1
// Third time create post with title Simple Post
UniqueSlug::generate(Post::class, 'Simple Post', 'slug');
// Output: simple-post-2
Let's assume separator is ''
empty.
// First time create user.
UniqueSlug::generate(User::class, 'akash', 'username', ''); // akash
// Second time create user.
UniqueSlug::generate(User::class, 'akash', 'username', ''); // akash1
// Third time create user.
UniqueSlug::generate(User::class, 'akash', 'username', ''); // akash2
public function create(array $data): Category|null
{
if (empty($data['slug'])) {
$data['slug'] = UniqueSlug::generate(Category::class, $data['name'], 'slug');
}
return Category::create($data);
}
UniqueSlug::generate($model, $value, $field, $separator);
/**
* Generate a Unique Slug.
*
* @param object $model
* @param string $value
* @param string $field
* @param string $separator
*
* @return string
* @throws \Exception
*/
public function generate(
$model,
$value,
$field,
$separator = null
): string
php artisan vendor:publish akash/laravel-unique-slug
return [
/*
|--------------------------------------------------------------------------
| Slug default separator.
|--------------------------------------------------------------------------
|
| If no separator is passed, then this default separator will be used as slug.
|
*/
'separator' => '-',
/*
|--------------------------------------------------------------------------
| Slug max count limit
|--------------------------------------------------------------------------
|
| Default 100, slug will generated like
| test-1, test-2, test-3 .... test-100
|
*/
'max_count' => 100,
];
You're open to create any Pull request.