Last active
May 4, 2021 08:53
-
-
Save pecuchet/abcb2ccad2cf9b322ee61af36ed89366 to your computer and use it in GitHub Desktop.
Laravel model trait to create unique slugs
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\Traits; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Str; | |
trait UniquelySuggable | |
{ | |
/** | |
* Trait users should implement this. | |
* @param Model $model | |
* @return string | |
*/ | |
abstract protected function slugify(Model $model): string; | |
/** @inheritDoc */ | |
protected static function boot() | |
{ | |
parent::boot(); | |
static::creating(function ($model) { | |
$slug = empty($model->slug) ? $model->slugify($model) : $model->slug; | |
$model->slug = $model->createUniqueSlug($slug); | |
}); | |
} | |
/** | |
* Create a unique slug. | |
* @param string $title | |
* @return string | |
*/ | |
protected function createUniqueSlug(string $title): string | |
{ | |
$slug = Str::slug($title); | |
$model = static::query() | |
->where('slug', 'REGEXP', "$slug(\-\d+)?") | |
->orderBy('slug', 'desc') | |
->first(['slug']); | |
if ($model) { | |
if (preg_match("#(-\d+)$#", $model->slug, $matches)) { | |
$index = (int)str_replace('-', '', $matches[1]); | |
return $slug . '-' . ($index + 1); | |
} | |
return "$slug-1"; | |
} | |
return $slug; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment