Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Manikanta's avatar

How to create a Unique slug

How to create a unique slug , when ever insert a form data into table ..?

In Codeignter simple load the slug library u can create , but laravel is it any easy way to create a unique slug . if i use str_slug('My slug input '). Its create a duplicates .

0 likes
3 replies
Mikeritteronline's avatar

Are you using eloquent?

The actual method doesn't validate against any values by default.

// Illuminate/Support/helpers.php

if (! function_exists('str_slug')) {
    /**
     * Generate a URL friendly "slug" from a given string.
     *
     * @param  string  $title
     * @param  string  $separator
     * @return string
     */
    function str_slug($title, $separator = '-')
    {
        return Str::slug($title, $separator);
    }
}

So, you have a couple options:

  1. Call str_slug() then test the returned value against your database (perhaps start by defining your slug column as unique so the database enforces the constraint). At this point do as WordPress and append separator + 1 (i.e., my-new-slug-1).

  2. Go ahead and append a unique string to your slugs by default (perhaps datestamp or post UUID).

Please or to participate in this conversation.