Laravel 9 Generate Multiple Slug URL Example Tutorial

laravel create multiple slugs example; In this tutorial, you will learn how to generate multiple slug URLs in the Laravel app. In this guide, we will describe how to create unique SEO friendly urls or slug in php laravel app and store slugs in the database using the id.

What is a slug?

Well, a slug is the part of a URL which tells more about a specific page on a website in an easy to read form. Additionally, it’s the part of the URL that explains the page’s content and a slug plays a significant role in the web application of a request.

How to Create Multiple Slug Url in Laravel 9

  • Step 1: Download New Laravel Project
  • Step 2: Update Database Details
  • Step 3: Create Migration and Model
  • Step 4: Create Controller File
  • Step 5: Register New Route
  • Step 6: View App in Browser

Download New Laravel Project

To best describe this tutorial, start with downloading the new laravel application.

Let us run the provided command to create the project; it is like a table in the restaurant where you sit and enjoy your meal.

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

Update Database Details

To make the database connection, you need to insert your database details in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DB_Name
DB_USERNAME=DB_Username
DB_PASSWORD=DB_Password

Create Migration and Model

Here is the command that plays a role in creating the model and migration files; these files will help declare the table into the database.

php artisan make:model Blog -m

In the app/Models/Blog.php file, you will define the values that you want to add in database table.

<?php

namespace App\Models;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Blog extends Model
{
    use HasFactory;
    
    protected $fillable = [ 
        'title', 
        'slug',
        'details' 
    ];

    public $timestamps = false;

    protected static function boot()
    {
        parent::boot();
        static::created(function ($blog) {
            $blog->slug = $blog->initSlug($blog->title);
            $blog->save();
        });
    }

    private function initSlug($title)
    {
        if (static::whereSlug($slug = Str::slug($title))->exists()) {
            $max = static::whereName($title)->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}-1";
        }

        return $slug;
    }
}

If you noticed in the previous step, we have added the DB values; similarly, in this step, you have to define the column’s properties in the database/migrations/create_blogs_table.php file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title', 120);
            $table->string("slug", 120);
            $table->text('details');             
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Create Controller File

Further, create a new controller; you may write plenty of valuable functions regarding database-related work in this controller file.

php artisan make:controller BlogController

Insert the provided code in the app/Http/Controllers/BlogController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;


class BlogController extends Controller
{
    public function index()
    {
        $blog = Blog::create([
            "title" => "The demo is in process",
            "slug" => "laravel-multiple-slug-urls-example",
            "details" => "Here is the slug demo"
        ]);

        dd($blog);
    }

}

Register New Route

We need to define a new route in the routes/web.php file; it will request the controller to create the slug URLs in the laravel app and print the output on the browser.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/blog', [BlogController::class, 'index']);

View App in Browser

By using the following command, we can run the laravel development server and view the app.

php artisan serve

Every time you hit the given URL, the list of the unique slugs will be created in database.

http://127.0.0.1:8000/blog

Laravel Generate Multiple Slug URL Example Tutorial

Summary

In this tutorial you have learned how to generate slug using the Str::slug service, furthermore you have also learned how to create unique slug in store in the database from scratch