Last active
April 19, 2022 13:20
-
-
Save vladimir-zarcanin/05dd497832d361084caaf369e1668381 to your computer and use it in GitHub Desktop.
Laravel automatically create unique slug on model created.
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; | |
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(); | |
}); | |
} | |
} |
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 | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.