Laravel 10 Generate Multi Unique Slug on Page Load Tutorial

Last Updated on by in Laravel

In this laravel slug generate example, we will elaborate how to generate dynamic multiple slug in the Laravel application.

This guide is surely going highlight every aspect that will be helpful to create a slug from the post name or title in the laravel application.

A slug is the url or human-readable unique identifier helps in finding a web page or web resource. A specific keyword or id denotes the slug.

You most probably use it when you want to refer to an item while retaining the ability to see at it.

Not just Laravel, but you can use this unique guide to implement slug feature in the previous versions of laravel using the profound eloquent approach.

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

This laravel generate multiple unique slug on page load example tutorial will help you achieve your goal to integrate the slug generation feature in laravel from scratch.

From now on, you won’t struggle to build this functionality for your next laravel web project.