I want to create a date based ticket ID for my Laravel system, like:
2103 0001 2103 0002 2103 0003
And then next month:
2104 0001 2104 0002 2104 0003
I’ve getted it working using this:
$date = Carbon::now(); $repairCount = Repair::where('code', 'LIKE', date('ym') . ' %')->count(); $repairCount++; $repairID = $date->format('ym') . " " . str_pad($repairCount,4,"0",STR_PAD_LEFT);
But this isn’t completely ‘waterproof’. When I delete a repair (not the last one). It counts the numbers and then takes the last one (so you get duplicate ID).
How to improve this?
Advertisement
Answer
Ok, I think I covered any issues completely, by using this (based on last()):
$date = Carbon::now(); $repairID = Repair::where('code', 'LIKE', date('ym') . ' %')->get()->last(); if ($repairID != null) { $repairID = substr($repairID->code, 5); $repairID++; } else { $repairID = 1; }
Then save it with:
$date->format('ym') . " " . str_pad($repairID,4,"0",STR_PAD_LEFT)
Please let me know if this can cause some unwanted/unexpected behaviour.