Laravel 8 Create Unique Slug Tutorial Example


Hi Guys,

In this example,I will lean you how to create unique slug in can easy nad simply create unique slug in laravel.

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

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


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;
Controller Code:
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...