Process to Generate Unique Slug Example in Laravel

Hello Artisan

In this tutorial we will go over the demonstration of how to create unique slug in laravel. This article i will show the source code detailed on laravel create unique slug example. i would like to share with you laravel generate unique url. So if you don't know to create unique slug in laravel then this how to generate unique slug in laravel tutorial is for you.

Sometime we need laravel use slug instead of id to show data in frontend for hiding id in url. So in this situation you can easily create unique slug in laravel 6, laravel 7 and laravel 8 version.

Sometime we need to create slug from title or other field of table but except id in your application. But it is must needed thing that you also need to create unique slug on that table.  Let's see how to create unique slug in laravel example:

app/Models/Product.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;

    }

}

 

And use this in your controller

namespace App\Http\Controllers;

use App\Models\Product;

use Illuminate\Http\Request;
  
class ProductController extends Controller

{

    public function index()

    {

        $product = Product::create([

            "title" => "Laravel 8 Image Upload"

        ]);

        dd($product);

    }

}

 

Read also: How to Create Custom Slug using Title in Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js