Last active
December 20, 2015 21:24
-
-
Save danrichards/2aa1dce28b5c964fe21a to your computer and use it in GitHub Desktop.
Retrieve a unique slug with your Laravel model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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