How to create unique slug or url in Laravel

In Laravel, creating SEO-friendly URLs or user-friendly URLs often deals with unique slugs for models. Slugs are derived from a model's title or name, but conflicts may arise if we do not implement unique slug logic. In this tutorial, we will discuss a practical solution to automatically generate unique slugs in Laravel.

make sure that we are going to create a unique slug for a single modal later on we will discuss how we can create a unique slug dynamically on multiple modals. because this tutorial guides you to implement a unique slug on a single modal so that you can also use the same method on multiple controllers to create a unique slug on different models.

To implement unique slug logic we will follow these simple steps:

Step 01: Install the Laravel application and setup the database and migration

Step 02: create a unique slug function in the controller 

Step 03: use the unique slug generator function to create record or update records.

Step 01: Install the Laravel application and setup the database and migration

If you have not set up your Laravel application then you can follow this tutorial Laravel 9 Installation from basic

Step 02: create a unique slug function in the controller 

Paste the below code in the below of your controller.
        
        public function createSlug($title, $id = 0)
{
    $slug = Str::slug($title);

    $allSlugs = $this->getRelatedSlugs($slug, $id);

    if (!$allSlugs->contains('slug', $slug)) {

        return $slug;
    }

    $i = 1;

    $is_contain = true;

    do {

        $newSlug = $slug . '-' . $i;

        if (!$allSlugs->contains('slug', $newSlug)) {

            $is_contain = false;

            return $newSlug;
        }

        $i++;
    } while ($is_contain);
}

protected function getRelatedSlugs($slug, $id = 0)
{
    return Post::select('slug')->where('slug', 'like', $slug . '%')

        ->where('id', '<>', $id)

        ->get();
}
        
    

Step 03: use the unique slug generator function to create record or update records.

While creating a record :

        
        public function store(Request $request)
    {

        $request->validate([
            'name' => 'required'
        ]);

        $post = new Post();
        $post->title = $request->input('title');
        //it will generate unique slug
        $post->slug = $this->createSlug($request->input('title'));  

        $post->save();

        $notification = array(
            'message' => 'Post created successfully',
            'alert-type' => 'success',
        );

        return redirect()->back()->with($notification);

    }
        
    

Related Post

While updating a record: make sure to pass the current post id when updating records it will prevent checking the current post slug.

        
        public function update(Request $request, $id)
    {

        $request->validate([
            'name' => 'required',
            'slug' => 'required',
        ]);

        $post = Post::find($id);
        $post->title = $request->input('title');

        //$id will exclude checking the currebt post slug
        $post->slug = $this->createSlug($request->input('slug'), $id);  

        $post->save();

        $notification = array(
            'message' => 'Post updated successfully',
            'alert-type' => 'success',
        );

        return redirect()->back()->with($notification);

    }
        
    

Leave a comment