Skip to content

Instantly share code, notes, and snippets.

@jstoone
Created November 25, 2014 19:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstoone/35ec8ac5b01c79b6e32c to your computer and use it in GitHub Desktop.
Save jstoone/35ec8ac5b01c79b6e32c to your computer and use it in GitHub Desktop.
Laravel: Generate unique slug
/*
* Does not need to be wrapped in a class, I often have this in my model,
* but abstract when used more than once.
* @soruce: http://chrishayes.ca/blog/code/laravel-4-generating-unique-slugs-elegantly
*/
class UniqueSlug {
public static function generateUniqueSlug($value) {
$slug = Str::slug($value);
$slugs = static::whereRaw("slug REGEXP '^{$slug}(-[0-9]*)?$'");
if ($slugs->count() === 0)
return $slug;
// get reverse order and get first
$lastSlugNumber = intval(str_replace($slug . '-', '', $slugs->orderBy('slug', 'desc')->first()->slug));
return $slug . '-' . ($lastSlugNumber + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment