How to Generate Multi Unique Slug on Page Load in Laravel 9

In this Laravel multi unique slug example, we will learn how to generate dynamic multiple slugs in a Laravel 9 application.

This guide will highlight every aspect that will be help you to create a slug by using a post name or title in a Laravel application.

A slug is a URL or human-readable unique identifier with keywords separated by dashes, ‘-‘. It helps to find a web page or resource. A specific keyword or id will denote the slug.

You can implement the slug feature in Laravel 8 as well as other previous versions of Laravel using a profound eloquent approach.

Generate Multiple Slug – Main Steps

Step 1: Install Laravel App

Open your command line and type in the following command to create a new Laravel application.

composer create-project --prefer-dist laravel/laravel laravel-slug-app

Navigate to the Laravel app.

cd laravel-slug-app

Step 2: Set up Database Connection

You may use XAMPP or any other local web server, to insert the database name, username and password in a .env file.

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

Step 3: Database Migration and Model

Now, you will have to generate the model and migration files. Type in the single command as shown below.

php artisan make:model Post -m

Once the command is executed, a new model and migration file have been generated. Therefore, you may now add values in these files to create a table in the database.

Updates 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 move to the app/database/migrations/create_posts_table.php file, and insert the appropriate 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');
    }
}

Step 4: 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

Step 5: Generate and Setup Controller

We will now 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 code given below.

<?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);
    }
}

Step 6: Add a New Route

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

Make sure that you have got inside the suggested route file and imported the controller at the top. You may define the route as shown 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

Type in the terminal the following command and assure to execute it to invoke the Laravel development server.

php artisan serve

You may now open the browser and type the URL on the address bar. Simultaneously, open the PhpMyAdmin window. Now each time you execute the URL below, a new slug will be generated in the database.

http://127.0.0.1:8000/post

Conclusion

The tutorial on Laravel generate multi unique slug on page load example will help to achieve your goal to integrate the slug generation feature from scratch.