Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Last active December 1, 2023 04:59
Show Gist options
  • Select an option

  • Save AnandPilania/a716e79a75403963fd1ec3a74cfca2a7 to your computer and use it in GitHub Desktop.

Select an option

Save AnandPilania/a716e79a75403963fd1ec3a74cfca2a7 to your computer and use it in GitHub Desktop.
Laravel: Generate unique slug
<?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