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

qyioma's avatar

Invoice number

I want to make an invoice number that will start from 001 again for the next day. As example, the last invoice no for today is 230209-110, then tomorrow, the invoice no should start with 230210-001. Can someone help me to settle this problem, thank you. Below is my code:

public function invoice(){

    $invoice_no = IncomingGetWeight::where ('invoice','<>','')->orderBy('id','desc')->first();


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

    if (!$invoice_no)
    {
    
    $newStringNum = $date."001";
    }
    else
    {
    $numberString = substr ($invoice_no->invoice,6,3);
    $number = intval($numberString);
    $newNumber = $number + 1;
    $newStringNum=$date.str_pad($newNumber, 3, '0', STR_PAD_LEFT);  
    }

    return $newStringNum;
}
0 likes
1 reply
qyioma's avatar
qyioma
OP
Best Answer
Level 1

[Solved(Can use the code below)]

public function invoice(){

$invoice_no = IncomingGetWeight::where ('invoice','<>','')->whereDate('created_at', '=', Carbon::today())->orderBy('id','desc')->first();
$date = Carbon::now()->format('ymd');

if (!$invoice_no)
{
    $newStringNum = $date."001";
}
else
{
    $numberString = substr ($invoice_no->invoice,6,3);
    $number = intval($numberString);
    $newNumber = $number + 1;
    $newStringNum=$date.str_pad($newNumber, 3, '0', STR_PAD_LEFT);  
}

return $newStringNum;

}

Please or to participate in this conversation.