Laravel 9 Create Unique Slug Tutorial Example

Apr 30, 2022 . Admin

Hi Guys,

In this example, I will lean you how to create a unique slug in laravel 9.you can easily and simply create a unique slug in laravel 9.

In this tutorial, I will give you an example of How to Generate Unique Slug in Laravel 9, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.

Let's see step by step to create a unique slug in laravel 9 example:

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Create Model
php artisan make:model Post
app/Models/Post.php
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title','slug'
    ];

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::created(function ($post) {
            $post->slug = $post->createSlug($post->title);
            $post->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;
    }
}
Step 3: Create Controller
php artisan make:controller PostController
App/Http/Controllers/PostController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Post;
use Illuminate\Http\Request;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::create([
            "title" => "Laravel Livewire CRUD"
        ]);
        dd($post);
    }
}

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

Laravel-Livewire-CRUD
Laravel-Livewire-CRUD-2
Laravel-Livewire-CRUD-3

It will help you...

#Laravel 9