Skip to content

Instantly share code, notes, and snippets.

@pecuchet
Last active May 4, 2021 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pecuchet/abcb2ccad2cf9b322ee61af36ed89366 to your computer and use it in GitHub Desktop.
Save pecuchet/abcb2ccad2cf9b322ee61af36ed89366 to your computer and use it in GitHub Desktop.
Laravel model trait to create unique slugs
<?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