Skip to content

Instantly share code, notes, and snippets.

@vladimir-zarcanin
Last active April 19, 2022 13:20
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 vladimir-zarcanin/05dd497832d361084caaf369e1668381 to your computer and use it in GitHub Desktop.
Save vladimir-zarcanin/05dd497832d361084caaf369e1668381 to your computer and use it in GitHub Desktop.
Laravel automatically create unique slug on model created.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory, UniqueSlug;
protected $fillable = [
'title','slug'
];
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::created(function ($post) {
$post->slug = $post->createSlug($post->title);
$post->save();
});
}
}
<?php
use Illuminate\Support\Str;
trait UniqueSlug
{
public function createSlug($name): string
{
if (static::withTrashed()->whereSlug($slug = Str::slug($name))->exists()) {
$max = static::withTrashed()->whereName($name)->latest('id')->skip(1)->value('slug');
if (isset($max[-1]) && is_numeric($max[-1])) {
return preg_replace_callback('/(\d+)$/', function ($mathces) {
return $mathces[1] + 1;
}, $max);
}
return "{$slug}-2";
}
return $slug;
}
}
@vladimir-zarcanin
Copy link
Author

Inspired by https://www.nicesnippets.com/blog/laravel-8-create-unique-slug-tutorial-example. I have a problem with soft deleted models and create unique slugs.
However, I hope it will can help somebody.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment