To create a unique slug in Laravel, you can use the str_slug
function and the unique
method on the Eloquent model.
Here’s an example of how you might create a unique slug for a blog post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title', 'body'];
/**
* Boot the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function ($post) {
$post->slug = str_slug($post->title);
if (static::whereSlug($post->slug)->exists()) {
$post->slug = "{$post->slug}-" . time();
}
});
}
}
This model will automatically create a unique slug for each blog post when it is created. If a post with the same slug already exists, the model will append a timestamp to the slug to make it unique.