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

qyioma's avatar

Increment Invoice no

How to write, if label_ID is empty, use $newStringNumber = $label_ID->code."-".$date."-"."001"; , else use the other code. Because the result for the first label ID right now only have ymd-3 running no. I dont know why the code is missing.

public function getlabel_ID(){

$label_ID = IncomingGetweight::where ('label_ID','<>','')->orderBy('id','desc')->first();

$date = Carbon::now()->format('ymd');

    if ($label_ID)
    {
        
        $newStringNumber = $label_ID->code."-".$date."-"."001";
    }
    else
    {
        $numberString = substr ($label_ID->label_ID,9,3);
        $number = intval($numberString);
        $newNumber = $number + 1;
        $newStringNumber = $label_ID->code."-".$date."-".str_pad($newNumber, 3, '0', STR_PAD_LEFT);  
}

    return $newStringNumber;
}
0 likes
7 replies
Tray2's avatar

If the query yields no results the variable is null, so you can just do

if (! $label_ID) {
	//assign the new one
} else {
	// Assign the existing one
}
qyioma's avatar

@Tray2 I already use this way, but the result only shows ymd-3 running no. The code still missing.

illuminatixs's avatar

Hi there,

Let's see how we can refactor this piece of code to make it more readable:

public function getlabel_ID(): string {
	// Change to the var naming as we are not only selecting "label_ID" but rather the entire model object.
	$matchingIncomingGetWeight = IncomingGetweight::where('label_ID', '<>', "")->orderBy('id', 'desc')->first();
	
	// Move the logic to its own function to keep the main function readable.
	return $this->buildStringNumber(Carbon::now(), $matchingIncomingGetWeight);
}

private function buildStringNumber(Carbon $date, IncomingGetweight $incomingGetWeight = null): string {
	// Now we can just directly return the value if $incomingGetWeight isn't null
	if (null !== $incomingGetWeight) {
		return $incomingGetWeight->code."-".$date->('ymd)."-"."001";
	}

	// Combine the seperated creation of a new number.
	$newNumber = ((int) substr($incomingGetWeight->label_ID, 9, 3)) + 1;

	// Directly return rather than also putting it into a var.
	// Do note that the 2nd param in str_pad sets the length: We substr with a 
	// length of 3 And you want to add 2 "0" before this, 
	// so in total we need a length of 5.
    return $label_ID->code."-".$date."-".str_pad($newNumber, 5, '0', STR_PAD_LEFT);
}

Hope this helps a bit.

jlrdw's avatar

@qyioma Also just FYI, some good ways to increment an invoice number has been in some past post. If not careful you could have a duplicate.

illuminatixs's avatar

@qyioma it was written dry (without testing) it’s just to give you an idea. the issue was in your str_pad , read the comments.

1 like

Please or to participate in this conversation.