Create unique slug without any package in laravel

author
1
3 minutes, 45 seconds Read

In this article, I will demonstrate the process of dynamically generating unique slugs for any models within Laravel 10. Our approach involves crafting distinctive slugs for tables existing within our Laravel application. By crafting a unified helper method and strategically invoking it, we can seamlessly generate these unique slugs. By establishing a solitary helper method and employing it within the store method of a controller, we gain the ability to effortlessly produce distinct slugs for diverse tables. When utilizing the helper method, it becomes necessary to provide certain parameters to facilitate the dynamic creation of slugs for various models. Let’s follow the steps,

Step 1: Create a helper file

At first, we will create a directory named Helpers inside the app directory. Then create a php file and name it helper.php

Step 2: Include this helper.php file in the composer.json

Now add the helper.php file in the composer.json file. Open the composer.json file located in the root directory of the laravel project. Then scroll down to the “autoload” section and add the helper.php with its path in the files array. Adding this file, you can access any function written inside this helper.php file across the entire application.

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

After that, run this command.

composer dump-autoload

Step 3: Write the slug-generating function inside the helper file

Let’s enhance the helper function with the following code. In this section, we will incorporate the necessary logic for generating exclusive slugs that are applicable to any given model. Inside the helper.php file,

function create_slug($sluggable_text, $model_name, $column_name = 'slug', $is_module = false, $module_name = null)
{
    // Use CamelCase for Model and Module Name
    if ($is_module) {
        $model_path = 'Modules\\' . ucwords($module_name) . '\Entities\\' . ucwords($model_name);
    } else {
        $model_path = '\App\Models\\' . ucwords($model_name);
    }

    $slug = Str::slug($sluggable_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;
}
PHP

Step 4: Create a unique slug from the controller

During this stage, we will generate distinct slugs for both posts and products by invoking the designated helper method. This versatile helper method can be accessed from any controller, enabling the generation of unparalleled slugs for various tables within the application. Let’s see an example,

PostController.php

Here, we make use of the create_slug() function from the helper, passing in the text that needs to be converted into a slug, the name of the model, and the designated column name within the Post::create([ ]) method. This operation culminates in the creation of a distinctive slug specifically tailored for the “posts” table.

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

        // If the column name is slug
        Post::create([
            'name' => $request->name,
            'slug' => create_slug($request->slug, 'Post'),
        ]);
        
        
        // If the column name is different, Do this
        Post::create([
            'name' => $request->name,
            'your_column_name' => create_slug($request->slug, 'Post', 'your_column_name'),
        ]);
    }
PHP

Optional Step: Create a unique slug inside a module from the controller

If you wish to employ this function within a Laravel module, you can seamlessly integrate it. Let’s consider a hypothetical scenario where you have a module named “ProductModule” having a model named “Product.” In this case, the model corresponds to the “products” table, with the designated column being “slug.”

 // Inside the controller of ProductModule Module
 public function store_product(Request $request)
    {
        $request->validate([
            'name'=>'required|max:191',
            'slug'=>'required|max:191',
        ]);

        Product::create([
            'name' => $request->name,
            'slug' => create_slug($request->slug, 'Product', 'slug', true, 'ProductModule'),
        ]);
        
        // Your Extra Logic
    }
PHP

By using this method, you can generate unique slugs for your entire application, which can speed up your development process.

We appreciate your support and are committed to providing you useful and informative content. We are thankful for your ongoing support
We appreciate your support and are committed to providing you with useful and informative content. We are thankful for your ongoing support
Share To:

Similar Posts

Comments

  1. avatar
    Sahin Giray says:

    Wow, your creativity and dedication shine as you’ve come up with a clever way to generate unique slugs for articles in Laravel, all without relying on any additional packages. Your code reflects your commitment to understanding the intricacies of web development. Keep up the fantastic work!

Leave a Reply

Your email address will not be published. Required fields are marked *