I am using Laravel 8 to create an application. Here I need to Generate an Order Number for every order. For this, I use Helper and write this code. It works the very first time, from the second time it shows "Undefined variable $last_number" from return line.
public static function OrderNumberGenerator($model, $trow, $length = 4, $prefix)
{
$data = $model::orderBy('id', 'desc')->first();
if (!$data) {
$og_length = $length;
$last_number = '';
} else {
$code = substr($data->$trow, strlen($prefix) 1);
$actual_last_number = ($code / 1) * 1;
$increment_last_number = $actual_last_number 1;
$last_number_length = strlen($increment_last_number);
$og_length = $length - $last_number_length;
$last_number_length = $increment_last_number;
}
$zeros = "";
for ($i = 0; $i < $og_length; $i ) {
$zeros .= "0";
}
return $prefix . '-' . $zeros . $last_number;
}
from my controller I use this:
Helper::OrderNumberGenerator(new OrderDetail, 'orderNo', 5, 'DRW');
CodePudding user response:
public static function OrderNumberGenerator($model, $trow, $length = 4, $prefix)
{
$last_number = '';
$data = $model::orderBy('id', 'desc')->first();
if (!$data) {
$og_length = $length;
} else {
$code = substr($data->$trow, strlen($prefix) 1);
$actual_last_number = ($code / 1) * 1;
$increment_last_number = $actual_last_number 1;
$last_number = strlen($increment_last_number);
$og_length = $length - $last_number;
$last_number = $increment_last_number;
}
$zeros = "";
for ($i = 0; $i < $og_length; $i ) {
$zeros .= "0";
}
return $prefix . '-' . $zeros . $last_number;
}
I think your code should be like that. I hope it is help you.
CodePudding user response:
You must define
$last_number = ' ';
before if statement When it exits from the if block, this variable is deleted from memory