Nikki
Nikki

Reputation: 215

Getting an invoice number to be generated in laravel

I'm trying to generate an invoice number, but I'm getting A non-numeric value encountered. I think I'm missing something but I'm not sure what it is.

Here is the invoiceNumber() code in my helpers.php

function invoiceNumber()
{
    $orders = App\Order::all();

    if($orders->isEmpty())
    {
        $invoice = 'arm0001';
        return $invoice;
    }

    foreach($orders as $order)
    {
        $latest = App\Order::latest()->first();

        if($latest->invoice_number == true)
        {
            $invoice = 'arm'.$latest->invoice_number+1;
            return $invoice;
        }
    }
}

and this is where I'm trying to get it to be taken

public function deliveryConfirmation()
{
    $menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
    $contacts = Contact::all();

    if(!Session::has('cart'))
    {
        return view('public.shopping-cart', compact('menus_child', 'contacts'));
    }

    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);

    $invoice_number = invoiceNumber();
    dd($invoice_number);

    return view('public.delivery-confirmation', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'invoice_number' => $invoice_number]);
}

I would really like to keep the 'ARM' in the database as well

Upvotes: 2

Views: 11081

Answers (4)

Ritesh Khatri
Ritesh Khatri

Reputation: 1301

You can increment you number by simply incremental ++ and keep your invoice number prefix. like,

$invoice = 'arm'.++$latest->invoice_number;

++$latest->invoice_number this will increment your number by 1. Hope it help you to achieve what you want.

Upvotes: 0

apokryfos
apokryfos

Reputation: 40730

The reason is because the operator precedence of . and + is the same and so they are therefore evaluated left to right.

So if you break it down you get:

(('arm'.$latest->invoice_number)+1) -> ('arm123'+1) 

where arm123 would be a non-numeric value.

In this case you need to force the evaluation order by using parentheses:

 'arm'.($latest->invoice_number+1)

Upvotes: 0

Nikki
Nikki

Reputation: 215

So after seeing everyone's answer and from my understanding, it looked like everyone was separating the integer from the string to get it to work and it got me thinking about doing a preg_replace(). so I've adjusted my code to look like this

function invoiceNumber()
{
    $latest = App\Order::latest()->first();

    if (! $latest) {
        return 'arm0001';
    }

    $string = preg_replace("/[^0-9\.]/", '', $latest->invoice_number);

    return 'arm' . sprintf('%04d', $string+1);
}

Upvotes: 1

Thierry Maasdam
Thierry Maasdam

Reputation: 1054

Try this:

$invoice = 'arm' . ((int)$latest->invoice_number + 1);

...and with leading zeros (ARM0001):

$invoice = 'arm' . (str_pad((int)$latest->invoice_number + 1, 4, '0', STR_PAD_LEFT));

Upvotes: 3

Related Questions