How to Generate Unique Slug in Laravel 8 Tutorial?

Share this Article
Reading Time: 6 minutes
1,708 Views

Inside this article we will see the concept of generate unique slug in laravel 8. It will be very easy to get the concept and implement in laravel 8 application.

We can use this same concept of slug generation with other versions of laravel as well. Inside this tutorial also we will understand how to generate unique slug in laravel using eloquent model events.

Let’s get started.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Learn Composer Installation Steps. Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at 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.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

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 /app/Models
  • 2021_03_15_030914_create_products_table.php Migration file at /database/migrations.

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

<?php

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

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
  • We are creating a products table with columns – name, slug & description

Migrate Migration

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

$ php artisan migrate

Open Product.php and write this updated code.

<?php

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()
    {
        parent::boot();

        static::created(function ($product) {

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

            $product->save();
        });
    }

    /** 
     * 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.

Here, we are checking that, slug should be unique of each inserted product.

Examples for some slug

laravel-8-product-upload

laravel-8-product-upload-2

laravel-8-product-upload-3

laravel-8-product-upload-4

Create Controller

Open terminal and run this artisan command to create controller file.

$ php artisan make:controller ProductController

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

Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        $product = Product::create([
            "name" => "Laravel 8 Sample Product",
            "description" => "Sample data"
        ]);

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

Create Route

Open web.php from /routes folder.

use App\Http\Controllers\ProductController;

//...

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

//...

Application Testing

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

$ php artisan serve

URL – http://127.0.0.1:8000/product

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 Generate Unique Slug in Laravel 8 in a very detailed way.

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.

Find More on Laravel 8 Articles here

Leave a Comment