Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Created November 30, 2023 12:34
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 eusonlito/bf0014040cd1f0965a1cf1322c717f28 to your computer and use it in GitHub Desktop.
Save eusonlito/bf0014040cd1f0965a1cf1322c717f28 to your computer and use it in GitHub Desktop.
Generate unique slugs
<?php
protected static function generateUniqueSlug(string $title): string
{
$slug = str_slug($title);
if (static::query()->where('slug', $slug)->doesntExist()) {
return $slug;
}
$last = static::query()
->selectRaw('CAST(REPLACE(`slug`, ?, "") AS UNSIGNED) `last`', [$slug.'-'])
->whereRaw('REPLACE(`slug`, ?, "") REGEXP "\-[0-9]+$"', [$slug])
->orderBy('last', 'DESC')
->value('last');
return $slug.'-'.($last + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment