Laravel 10 Generate Multi Unique Slug on Page Load Tutorial

Last Updated on by in Laravel

In this tutorial, you’ll learn how to generate multiple unique slugs on page load in a Laravel application.

A slug is a URL-friendly version of a name or title, commonly used for routing and SEO purposes. However, generating a unique slug can be tricky, especially when multiple records have similar names.

In this comprehensive guide, we’ll show you step-by-step how to generate dynamic slugs using the Eloquent model in Laravel. 

Here’s what we’ll cover in this tutorial:

  • Setting up the model: Define the model and specify which fields are fillable.
  • Boot method: Automatically generate a slug upon record creation using the boot method.
  • Creating the generateSlug function: Write the logic to create a unique slug from the name.
  • Testing the implementation: Test the code by creating multiple records with similar names to ensure slugs are unique.

By the end of this tutorial, you will understand how to generate unique slugs for records in your Laravel application, which can improve your app’s routing and SEO.

How to Generate Multiple Slug in Laravel 10 App

  • Step 1: Install Laravel App
  • Step 2: Evoke Database Connection
  • Step 3: Set Up Model and Migration
  • Step 4: Run Database Migration
  • Step 5: Generate and Setup Controller
  • Step 6: Add New Route
  • Step 7: Start Laravel App

Install Laravel App

Initialize the first step with laravel application installation, hence open console and execute the following command:

composer create-project --prefer-dist laravel/laravel laravel-demo

Move into laravel app.

cd laravel-demo

Evoke Database Connection

You can use MAMP or XAMPP as a local web server, insert the database name, username and password in the .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

Set Up Model and Migration

In this step, you have to generate model and migration files. It can be done by using a single command, hence execute the following command.

php artisan make:model Post -m

After running the suggested command, new model and migration files have been generated, and you will add values in these files to create a table in the database.

Update code in app/Models/Post.php file.

<?php
namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    use HasFactory;
    
    protected $fillable = [ 
        'name', 
        'slug',
        'description' 
    ];
    public $timestamps = false;
    protected static function boot()
    {
        parent::boot();
        static::created(function ($post) {
            $post->slug = $post->generateSlug($post->name);
            $post->save();
        });
    }
    private function generateSlug($name)
    {
        if (static::whereSlug($slug = Str::slug($name))->exists()) {
            $max = static::whereName($name)->latest('id')->skip(1)->value('slug');
            if (isset($max[-1]) && is_numeric($max[-1])) {
                return preg_replace_callback('/(\d+)$/', function($mathces) {
                    return $mathces[1] + 1;
                }, $max);
            }
            return "{$slug}-2";
        }
        return $slug;
    }    
}

Now, get into the app/database/migrations/create_posts_table.php, and you have to insert the table values into this migration file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name', 150);
            $table->string("slug", 150);
            $table->text('description');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Run Database Migration

All the migration and model files have been updated now, and you have to execute the command to run migrations.

php artisan migrate

Generate and Setup Controller

Let us generate a new controller file using the following composer command.

php artisan make:controller PostController

Next, you have to open the app/Http/Controllers/PostController.php and update the file with the given code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        $post = Post::create([
            "name" => "Back to future",
            "slug" => "laravel-generate-multi-slug-on-load",
            "description" => "This is just the laravel slug example"
        ]);
        dd($post);
    }
}

Add New Route

Now, you need to have a route defined in the routes/web.php file, and this route will be the endpoint or url for generating the slug.

Ensure that you have got inside the suggested route file and imported the controller at the top, and defined the route as mentioned below.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/post', [PostController::class, 'index']);

Start Laravel App

Head over to the terminal’s window, start typing the following command and make sure to execute it to invoke the Laravel development server.

php artisan serve

Then open the browser and type the url on the address bar; simultaneously, open the PHPMyAdmin window.

You will see every time you execute the following url, and a new slug is generated in the database.

http://127.0.0.1:8000/post

Laravel Generate Multi Unique Slug

Conclusion

Generating unique slugs for similar names in Laravel is easy with the right logic in place. This tutorial showed you how to create a unique slug for each record in your application, helping improve your routing and SEO.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.