Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to customize slug uniqueness resolution #611

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions resources/config/sluggable.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@

'unique' => true,

/**
* If the slug is not unique and you want to try to make it unique by replacing
* some other parts of the slug, you can set this to a closure which accepts
* the base slug, the separator, and a Collection of the other "similar" slugs.
* The closure should return the new unique slug to use, if the slug is still not
* unique, it will append a suffix.
*/
'uniqueUsing' => null,

/**
* If you are enforcing unique slugs, the default is to add an
* incremental value to the end of the base slug. Alternatively, you
Expand Down
14 changes: 14 additions & 0 deletions src/Services/SlugService.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,20 @@ protected function makeSlugUnique(string $slug, array $config, string $attribute
}
}

// If uniqueUsing is set to a closure, use it to generate a new "unique" slug
if (isset($config['uniqueUsing']) && is_callable($config['uniqueUsing'])) {
$using = $config['uniqueUsing'];

// Generate mew slug using the closure
$slugUsing = $using($slug, $separator, $list);

// Remove uniqueUsing from the config to avoid infinite loop
unset($config['uniqueUsing']);

// Call makeSlugUnique again with the new slug to ensure it's unique
return $this->makeSlugUnique($slugUsing, $config, $attribute);
}

$method = $config['uniqueSuffix'];
$firstSuffix = $config['firstUniqueSuffix'];

Expand Down