Created
November 30, 2023 12:34
-
-
Save eusonlito/bf0014040cd1f0965a1cf1322c717f28 to your computer and use it in GitHub Desktop.
Generate unique slugs
This file contains 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
<?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