Laravel 8 Create Unique Slug Tutorial Example

9864 views 1 year ago Laravel

In this article, we will provide example of how to generate unique slug in laravel. You will easily understand a concept of unique slug generator laravel example. I explained simply step by step laravel generate unique slug. if you want to see example of laravel create unique slug example then you are a right place.

So let's get started with laravel generate slug before save.

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.

Below is the Product model file. In the model class, create createSlug() method which create unique slug. Also create a boot() method which will trigger createSlug() method everytime when new model is created.

<?php
namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
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();
        });
    }
    /** 
     * create slug
     *
     * @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;
    }
}

In the controller class, call create method of model class.

<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
    /**
     * create a new product
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $product = Product::create([
            "title" => "Samsung s11 Pro"
        ]);
        dd($product);
    }
}

Now, it will create slug as below:

samsung-s11-pro
samsung-s11-pro-1
samsung-s11-pro-2

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]