Search
Laravel 13 Generate Unique Slug For Any Models Without Package

Laravel 13 Generate Unique Slug For Any Models Without Package

Hello devs,

In this post I will show you how to generate unique slug  in laravel 13 dynamically for any models. We will create unique slug for any tables present in our laravel application. We will create a helper method and call it where we need to generate unique slug. Just create a single helper method and calling this method from store method inside a controller we can easily create unique slug for any tables. While call the helper method we have to pass some parameters so that we can create slug for any models dynamically. To do this let's follow the bellow steps:

Step 1: Create helper.php

At first we will create a directory Helper inside app folder and then create a helper.php file inside Helper directory. 

helper

Step 2: Include helper.php  in composer.json

we have to include the helper.php file in our composer.json, so that when we autoload, it will load the file globally. After do tis we will use the helper file in our entire application.

composer.json

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files": [
            "app/Helper/helper.php"
        ]
    },

Don't forget to run the autoload command after include the helper file

composer dump-autoload

Step 3: Update the helper.php

Now we will update the helper with the below code. Here we implements the logic to generate unique slug for any models.

helper.php

<?php

function create_slug($slug_gable_text, $model_name,$column_name)
{
    // Use CamelCase for Model Name

    $model_path = '\App\Models\\' . ucwords($model_name);

    $slug = Str::slug($slug_gable_text);
    $check = true;

    do {
        $old_category = (new $model_path)->where($column_name, $slug)->orderBy('id', 'DESC')->first();

        if ($old_category != null) {
            $old_category_name = $old_category->$column_name;
            $exploded = explode('-', $old_category_name);

            if (array_key_exists(1, $exploded)) {
                $number = end($exploded);

                if (is_numeric($number) == true) {
                    $number = (int)$number;
                    array_pop($exploded);

                    $final_array = array_merge($exploded, Arr::wrap(++$number));

                    $slug = implode('-', $final_array);
                } else {
                    $slug .= '-1';
                }
            } else {
                $slug .= '-1';
            }
        } else {
            $check = false;
        }
    } while ($check);

    return $slug;
}

Step 4: Create unique slug from controller

In this step we will generate unique slug for category and posts calling the helper method. You can call this helper method from any controller to generate unique slug for ny tables.

Let's see some example:

CategoryController.php

Here we call the the create_slug() method from helper and pass slugable text, model name, and column name inside Category::create([ ]) method. This will generate a unique slug for categorie table.

    public function store_category(Request $request)
    {
        $request->validate([
            'name'=>'required|max:191',
            'slug'=>'required|max:191',
        ]);

        $slug = Str::slug($request->name);
        Category::create([
            'name'=>$request->name,
            'slug'=>create_slug($slug, 'Category', 'slug'),
        ]);
        return back();
    }

Let's see another example for Post:

PostController.php

We need to change only the model name and the unique slug will generate automatically.

    public function store_post(Request $request)
    {
        $request->validate([
            'title'=>'required|max:191',
            'slug'=>'required|max:191',
        ]);

        $slug = Str::slug($request->title);
        Post::create([
            'title'=>$request->title,
            'slug'=>create_slug($slug, 'Post', 'slug'),
        ]);
        return back();
    }

This way you can create unique slug for your entire application. Hope this will faster your development work. Thanks to read this article.

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support 

 

You May Read Bellow Articles:

Laravel 13 live search data in a table using ajax. 

How to send SMS in laravel 9 using Twilio SMS API-Webjourney

Laravel 13 pdf invoice generate and download with barryvdh dompdf

How to create multi language website by laravel 13

Laravel image crud with radio, checkbox, email, date, text, number, color, select box

Laravel 13 multiple form validation on the same page-WebJourney

 Laravel 13 Breeze Authentication - WebJourney

Laravel 13 Ajax jQuery Crud with Pagination and Live Search

Laravel Naming Conventions Accepted by Laravel community

Laravel Shorter and More Readable Syntax - WebJourney

Tags

  • Share This: