Reputation: 7138
I have piece of code to make order numbers like $order->order_no = 'TXT'.date('Ymd').'001';
this simply make results like: TXT20190213001
my issue is how to make 001
part dynamic in order to increment it like 001
002
003
and so on?
Upvotes: 1
Views: 10580
Reputation: 9045
// Get the last order id
$lastorderId = Order::orderBy('id', 'desc')->first()->order_no;
// Get last 3 digits of last order id
$lastIncreament = substr($lastorderId, -3);
// Make a new order id with appending last increment + 1
$newOrderId = 'TXT' . date('Ymd') . str_pad($lastIncreament + 1, 3, 0, STR_PAD_LEFT)
However, this will let you have max 999 numbers. You can have 001-999 fo everyday so you can have max 999 orders per day to no exceed 3 digit increments for a day.
To simplify :
You can use table's auto incremented primary key and add leading zeros to it.
$orderStmt = DB::select("SHOW TABLE STATUS LIKE 'orders'");
$nextPrimaryKeyId = $orderStmt[0]->Auto_increment;
Now you can add leading zeros :
$nextPrimaryKeyId = str_pad($nextPrimaryKeyId, 6, 0);
// Above will make increment id 23 as 000023
and then use it inside new order.
or.. You can use a uuid package to accomplish the same.
Upvotes: 3