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 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

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 = [

     * Boot the model.
    protected static function boot()

        static::created(function ($post) {
            $post->slug = $post->createSlug($post->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;
Step 3: Create Controller
php artisan make:controller PostController
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"

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


It will help you...

#Laravel 9