---
description: >-
  https://www.itsolutionstuff.com/post/laravel-generate-unique-slug-exampleexample.html
---

# Laravel Generate Unique Slug Example (ok)

C:\xampp\htdocs\reset\routes\web.php

```
<?php
use Illuminate\Support\Facades\Route;
use App\Models\User;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/test', [ProductController::class, 'index'])->name('home');

```

C:\xampp\htdocs\reset\database\migrations\2022\_05\_16\_051938\_create\_products\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('products', function (Blueprint $table) {
      $table->id();
      $table->string('title');
      $table->string('detail');
      $table->string('slug')->unique();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('products');
  }
}
```

C:\xampp\htdocs\reset\app\Models\Product.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Product extends Model {
  use HasFactory;
  protected $fillable = [
    'title', 'detail', 'slug',
  ];
  /**
   * Boot the model.
   */
  protected static function boot() {
    parent::boot();
    static::created(function ($product) {
      $product->slug = $product->createSlug($product->title);
      $product->save();
    });
  }
  /**
   * 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;
  }
}
```

C:\xampp\htdocs\reset\app\Http\Controllers\ProductController.php

```
<?php
namespace App\Http\Controllers;
use App\Models\Product;
class ProductController extends Controller {
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index() {
    $product = Product::create([
      "title"  => "Laravel 8 Image Upload",
      'detail' => "detail",
    ]);
    dd($product);
  }
}
```

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FbTmxs0I8WMJp0qTEbci4%2FScreenshot_5.png?alt=media\&token=d455861c-d9c1-446c-82d0-4b01ac59eb92)



## Laravel Generate Unique Slug Example

By Hardik Savani April 7, 2021 Category : Laravel![](https://a.vdo.ai/core/assets/img/cross.svg)PlayUnmuteLoaded: 1.17%Fullscreen[![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)](https://vdo.ai/?utm_medium=video\&utm_term=itsolutionstuff.com\&utm_source=vdoai_logo)Hello,

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, laravel 8 and laravel 9 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:

**app/Models/Product.php**

```
<?php  namespace App\Models;  use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Str;  class Product extends Model{    use HasFactory;      protected $fillable = [        'title', 'detail', 'slug'    ];      /**     * Boot the model.     */    protected static function boot()    {        parent::boot();          static::created(function ($product) {            $product->slug = $product->createSlug($product->title);            $product->save();        });    }      /**      * 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:**

```
<?php  namespace App\Http\Controllers;  use App\Models\Product;use Illuminate\Http\Request;  class ProductController extends Controller{    /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */    public function index()    {        $product = Product::create([            "title" => "Laravel 8 Image Upload"        ]);        dd($product);    }}
```

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

Read Also: [Laravel Livewire Click Event Example](https://www.itsolutionstuff.com/post/laravel-livewire-click-event-exampleexample.html)

```
laravel-8-image-uploadlaravel-8-image-upload-2laravel-8-image-upload-3laravel-8-image-upload-4
```

now you can try it and check it.

i hope it can help you...
