Skip to content

Instantly share code, notes, and snippets.

@fvanzeijl
Last active June 6, 2023 14:29
Show Gist options
  • Save fvanzeijl/a1839d7048906de03658aa1d76698aa7 to your computer and use it in GitHub Desktop.
Save fvanzeijl/a1839d7048906de03658aa1d76698aa7 to your computer and use it in GitHub Desktop.
Custom Sequence Number Generation for Order
<?php
// Based on code-snipped in laracasts-discussion by bobbybouwmann (https://github.com/bobbybouwmann)
// https://laracasts.com/discuss/channels/general-discussion/custom-sequence-number-generation-for-order?reply=70649
// -----------------------------------------------------------------------------------------------------------------
function getNextOrderNumber()
{
// Get the last created order
$lastOrder = Order::orderBy('created_at', 'desc')->first();
// Set Prefix
$prefix = date('Y');
// Set db-field
$field = 'order_id';
// Set length of incrementing number
$length = 6;
if (!$lastOrder) {
// We get here if there is no order at all
// If there is no number set it to 0, which will be 1 at the end.
$number = 0;
} else {
// If we have ORD2023000001 in the database then we only want the number
// So the substr returns this 000001
$number = substr($lastOrder->{$field}, strlen($prefix));
}
// Reset incrementing no if prefix has changed (e.g. in new year)
if (substr($lastOrder->order_no, 0, strlen($prefix)) !== $prefix) {
$number = 0;
}
// Add the string in front and higher up the number.
// the %05d part makes sure that there are always 6 numbers in the string.
// so it adds the missing zero's when needed.
return sprintf('%s%0' . $length . 'd', $prefix, intval($number) + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment