Created
November 29, 2023 16:40
-
-
Save MrPunyapal/2b1cfdd2c4ace0e14df31e65bbd93b38 to your computer and use it in GitHub Desktop.
Efficient Laravel Slug Generation: Unique, Sleek, and No Looping π
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 | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Factories\HasFactory; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Facades\DB; | |
class Blog extends Model | |
{ | |
use HasFactory; | |
protected $guarded = []; | |
public static function boot() | |
{ | |
parent::boot(); | |
static::creating(function ($post) { | |
// When creating a new post, automatically generate a unique slug | |
$post->slug = static::generateUniqueSlug($post->title); | |
}); | |
} | |
protected static function generateUniqueSlug($title) | |
{ | |
// Generate a base slug from the post title | |
$slug = str($title)->slug(); | |
// Check if a post with the same slug doesn't already exist | |
if (static::whereSlug($slug)->doesntExist()) { | |
// If no existing post has the same slug, return the base slug | |
return $slug; | |
} | |
// Find the maximum numeric suffix for slugs with the same base | |
$max = static::query() | |
->where('slug', 'like', $slug . '-%') | |
->max(DB::raw('CAST(SUBSTRING_INDEX(slug, "-", -1) AS SIGNED)')); | |
// If there are no slugs with the same base, or the max value is null, append '-2' | |
if ($max === null) { | |
return $slug . '-2'; | |
} | |
// Append the next numeric suffix to the base slug | |
return $slug . '-' . ($max + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
better version π€― by @eusonlito