Last active
December 1, 2023 04:59
-
-
Save AnandPilania/a716e79a75403963fd1ec3a74cfca2a7 to your computer and use it in GitHub Desktop.
Laravel: Generate unique slug
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
| <?php | |
| namespace App\Models; | |
| use Illuminate\Database\Eloquent\Factories\HasFactory; | |
| use Illuminate\Database\Eloquent\Model; | |
| class Blog extends Model | |
| { | |
| use HasFactory; | |
| protected $guarded = []; | |
| public static function boot() | |
| { | |
| parent::boot(); | |
| static::creating(function ($post) { | |
| $post->slug = static::generateUniqueSlug($post->title); | |
| }); | |
| } | |
| 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