Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maaz's avatar
Level 2

How to generate Item code for different products

Hey there, I have a migration table like this

   public function up()
    {
        Schema::create('purchase_details', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_id');
            $table->string('item_code');
            $table->string('item_name');
            $table->float('unit_price');
            $table->float('qty');
            $table->flat('discount_on_all')->default(0);
            $table->float('net_amount');
            $table->timestamps();
        });
    }

i want to generate item_code for a product while insertion, the rest of the fields are dynamic. do I don't want random number generators, should be like this "item001", or any other prefer way

0 likes
8 replies
newbie360's avatar

combine two column (and also 'unit_price' ??) to one column item_id (FK)

$table->string('item_code');
$table->string('item_name');

if use "item001", how you know the number of 0 zero give to str_pad()

1 like
neilstee's avatar
neilstee
Best Answer
Level 34

@maaz how about you use the id of the puchase_details that you created so that you have a unique item_code?

// after you created the purchase_details

$itemCode = 'item' . str_pad($purchase_details->id, 4, '0', STR_PAD_LEFT);
$purchase_details->item_code = $itemCode;
// item_code will be item0001 if id is 1, you get the point

$purchase_details->save();

and if you want to expand to item00000001 just change 4 to 8 or what you prefer.

1 like
maaz's avatar
Level 2

thanks a lot let me try :)

neilstee's avatar

@newbie360 nope, if your $id = 122 the item_code will be item0122

that's why it's very important to know what is the possible length of the purchase_details, let's say the possible is ranging between 1,000,000 and 10,000,000 records then we can use 8 as length to have item00000001 or if id is 32456 then it will be item00032456

@maaz please note on this

1 like
newbie360's avatar

@neilstee yup, i know ;)

because the item id is keep increasing, so can't exactly know the number to pad

newbie360's avatar

@maaz

   public function up()
    {
        Schema::create('purchase_details', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_id');
            $table->unsignedBigInteger('item_id');
            $table->float('qty');
            $table->flat('discount_on_all')->default(0);
            $table->float('net_amount');
            $table->timestamps();
            $table->foreign('item_id')->references('id')->on('items');
        });
    }

so the item_id is belongsTo items table id

the items table

| id  | name    | price |
| --- | ------  | ----- |
| 1   | ASUS    | 900   |
| 2   | ASUS    | 888   |
| 3   | Linksys | 50    |

Please or to participate in this conversation.