How to add prefix with Auto Increment column in Laravel

In this tutorial we will discuss, how to save auto-increment column with prefix in the database in laravel.

Laravel auto increment with prefix

We want to add a database cloumn which value addition of a static string and auto increment column. Let understand by example

We have a products table and it contain a unique product_id column which combined auto increment column and string like "PRODUCT_1". In simple way first we save product data and after update product_id by getting last saved data. But laravel provide boot method in model which run when data create so we use it in model see below example.

Products Table

products
  id, name, price, product_id

ProductController

Run this command for make ProductController "php artisan make:controller ProductController"

<?php

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

class ProductController extends Controller{

  public function store(Request $request){
    $data = [
      'name' => "test product",
      'price' => "1000"
    ];
    Product::create($data);
  }
}

Product Model

Product model have a boot method which run every time when model call and in that boot method use created() method which create product_id data when data create threw model.

<?php

namespace App\Models;

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

class Product extends Model
{
  use HasFactory;
  protected $guarded = [];

  protected static function boot(){
    parent::boot();

    static::created(function ($model) {
      $model->product_id = "PRODUCT_" . $model->id;
      $model->save();
    });
  }
}
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links