Home > database >  Increase new invoice number, sometimes duplicated
Increase new invoice number, sometimes duplicated

Time:09-21

I have this code-snippet:

$invoiceNumber = InvoiceNumbers::where('vendor', $request->user()->vendorId)->orderByDesc('invoice_number')->limit(1)->first();
$invoiceNumber ? $newInvoiceNumber = $invoiceNumber->invoice_number   : $newInvoiceNumber = 1;
$invoiceNumber = InvoiceNumbers::create(['invoice_number' => $newInvoiceNumber, 'vendor' => $request->user()->vendorId]);

Unfortunately sometimes, when the scripts runs two times parallel the same invoice number would be created in two entries - Is there an option how I can prevent this? Like with table locks or something like this?

Thanks in advance!

CodePudding user response:

There's a difference between invoicenumber and invoicenumber;

<?php
    $count = 1;
    $var = $count  ; #count is assigned to $var, then  1 added.
    #var now equals 1, count = 2
    echo $var; #outputs 1

    $count = 1;
    $var =   $count; #count is incremented, then assigned
    echo $var; #outputs 2
?>

This might solve your problem, but it's advised that if the invoice number is unique and auto increments it would be best to do this on the database level. You can handle this in one of two ways:

  • Make InvoiceNumber unique and AutoIncrements, below is sql code, replace it with your relevant column and table name

    ALTER TABLE invoices MODIFY InvoiceNumber INT NOT NULL AUTO_INCREMENT UNIQUE;

  • Make invoice number unique, and wrap the insert in a try-catch{} statement, that increments it again if the SQL throws an error.

    <?php
        try{
            $invoice = new Invoice;
            $invoice->invoice_number = $invoice_number;
            $invoice->save();
        }catch (Exception $e) {
            $invoice_number  ;
            $invoice = new Invoice;
            $invoice->invoice_number = $invoice_number;
            $invoice->save();
        }
    ?>
    
  • Related