Skip to content

Instantly share code, notes, and snippets.

@danrichards
Last active December 20, 2015 21:24
Show Gist options
  • Save danrichards/2aa1dce28b5c964fe21a to your computer and use it in GitHub Desktop.
Save danrichards/2aa1dce28b5c964fe21a to your computer and use it in GitHub Desktop.
Retrieve a unique slug with your Laravel model.
/**
* Find a unique slug.
*
* @see https://github.com/cocur/slugify
* @param $text
*
* @return string
*/
public static function getUniqueSlug($text)
{
$slug = substr(Slugify::slugify($text), 0, 255);
$unique = boolval(static::where('slug', '=', $slug)->count());
$counter = 1;
while (! $unique) {
$postfix = "-{$counter}";
$slug = $counter == 1
? substr($slug, 0, 255-strlen($postfix)).$postfix
: substr($slug, 0, strlen($slug) - strlen("-".((string) ($counter-1))));
$unique = boolval(static::where('slug', '=', $slug)->count());
$counter++;
}
return $slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment