Spread the love

In this article we are going to create slug from any input field. slug is useful search engine optimization and also from security perspective because in some case we use primary id or unique id of table to fetch the detail in page but its not recommended way to show number in URL. Showing ID in URL can be open to SQL injection which lead to website hacking.

There is 3 ways to create the slug in Laravel

  1. Create save event in model
  2. Slug using trait
  3. Slug using package

Create slug using save event

In this way we will create a event in every model to generate the slug and save into the table.

Step 1: Create a model

First step is to create the model using artisan command or you can choose your any model

php artisan make:model Post

it will generate a Post model in app\Model folder.

Step 2: Register the create event

Now, register a createed event on every new row creation


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 static function boot()

        static::created(function ($post) {
            $post->slug = $post->generateUniqueSlug($post->title);

    private function generateUniqueSlug($name,$counter=0,$slugField="slug")
        $updatedName = $counter==0?$name:$name."-".$counter;
        if (static::where($slugField,$slug = Str::slug($updatedName))->exists()) {
               return  $this->generateUniqueSlug($name,$counter+1);
        return Str::slug($updatedName);

Here , we registered a event static::created and then generated a unique slug by checking the existancy of slug recursively in database.

Step 3: Create the route and save post

This is the time to check our implementation, so we need to create the route and create a new post


use Illuminate\Support\Facades\Route;
use App\Models\Post;


    $post=new Post;
    $post->title="This is a test";
    $post->description="This is a test";

now we can check in browser and below is screenshot

Slug generation in laravel

Leave a Reply