How To Generate Unique Slug in Laravel 10 Tutorial

Share this Article
Reading Time: 6 minutes

Inside this article we will see the concept of How To Generate Unique Slug in Laravel 10 Tutorial. Article contains classified information about How to generate SEO-friendly slugs in Laravel 10.

A URL slug is a human-readable portion of a URL that identifies a certain page or resource on a website. It is usually a concise, descriptive, and easy-to-remember language that represents the content or title of the page.

Slugs are frequently used in search engine optimisation (SEO) to increase the ranking of a website in search results by making URLs more user-friendly.

For example, in the URL, “how-to-write-a-blog-post” is the slug.

Read More: How To Get HTTP Hostname In Laravel 10 Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve


Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.


Read More: How to Check If a File Exists in Laravel 10 Tutorial

Create Model & Migration

Open project into terminal and run this command to create model and migration file.

Model file is one which helps application to communicate with database table and migration file creates schema of table.

$ php artisan make:model Product -m

This command create two different files – a Model file and a Migration file. -m is for migration file.

  • Proudct.php model file inside /app/Models folder.
  • 2023_03_15_030914_create_products_table.php Migration file inside /database/migrations.

Open {timestamp}_create_products_table.php migration file and write this update code.


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

return new class extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('products', function (Blueprint $table) {
            $table->string("name", 70);
            $table->string("slug", 100)->nullable();

     * Reverse the migrations.
     * @return void
    public function down()

Run Migration

Back to terminal and run this artisan migrate command to run migrations.

$ php artisan migrate

Table: products

Open Product.php from /app/Models folder and write this following code into it.


namespace App\Models;

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

class Product extends Model
    use HasFactory;

    protected $fillable = [
        'name', 'slug', 'description'

    public $timestamps = false;


     * Boot the model.


    protected static function boot()

        static::created(function ($product) {

            $product->slug = $product->createSlug($product->name);


     * Write code on Method
     * @return response()
    private function createSlug($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;

whereSlug is dynamic method created from the name of column. where{ColumnName}. whereName() is for name column.


We are checking that slug should be unique of every inserted product.

Examples for some slug





Read More: Laravel 10 How To Change Name And From Address in Email

Create Application Controller

Back to terminal and run this artisan command

$ php artisan make:controller ProductController

It will create a file ProductController.php inside /app/Http/Controllers folder.

Open this controller file and write this code into it.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
    public function addProduct()
        $product = Product::create([
            "name" => "Laravel 10 Sample Product",
            "description" => "Sample data"

  • Create & Save product into database table “products”.
  • Automatically the boot method what we have created in Product model will be used. We have used the concept of model event static::created
  • Product::create(), we have passed name and description value and also slug value automatically comes from model and will insert into table.

Add Route

Open web.php from /routes folder. Add this route into it.

use App\Http\Controllers\ProductController;

Route::get('product', [ProductController::class, 'addProduct']);


Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve


When you hit this url multiple times, it will insert new product rows inside products table. One thing we can notice is here about generated slug value, It is unique for all rows.

We hope this article helped you to learn about How To Generate Unique Slug in Laravel 10 Tutorial in a very detailed way.

Read More: Laravel 10 How To Add Image Into PDF Using DomPDF Library

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.