Laravel Generate Unique Slug Example


In this tutorial we will go over the demonstration of laravel generate unique slug. This article goes in detailed on laravel create unique slug example. i would like to share with you laravel generate slug before save. i would like to share with you how to generate unique slug in laravel.

you can easily create unique slug in laravel 6, laravel 7 and laravel 8 version.

Sometime we need to create slug from title with your application. but you also need to create unique slug on that table. might be user will enter same title then it should automatically generate unique slug. i will give you simple example step by step how to generate unique slug in laravel using eloquent model events.

Let’s see step by step to create unique slug in laravel example:



namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

use IlluminateSupportStr;

class Product extends Model


use HasFactory;

protected $fillable = [

'title', 'detail', 'slug'



* Boot the model.


protected static function boot()



static::created(function ($product) {

$product->slug = $product->createSlug($product->title);





* Write code on Method


* @return response()


private function createSlug($title){

if (static::whereSlug($slug = Str::slug($title))->exists()) {

$max = static::whereTitle($title)->latest('id')->skip(1)->value('slug');

if (is_numeric($max[-1])) {

return preg_replace_callback('/(d+)$/', function ($mathces) {

return $mathces[1] + 1;

}, $max);


return "{$slug}-2";


return $slug;



Controller Code:


namespace AppHttpControllers;

use AppModelsProduct;

use IlluminateHttpRequest;

class ProductController extends Controller



* Display a listing of the resource.


* @return IlluminateHttpResponse


public function index()


$product = Product::create([

"title" => "Laravel 8 Image Upload"





now if you create multiple time same title record then it will create slug as bellow:





now you can try it and check it.

i hope it can help you…

Leave a Comment