I am building an Laravel application to generate sales invoices. Multiple people from multiple companies generate invoices at a time. I have a table for Invoices as invoice_table where id is primary key and number is unique
id | company_id | series | number | amount
Now to generate invoice number what I do is; for a particular company take count and add 1 to that.
//assume $inv->prefix is a string which gives me series for particular company.
$series = Invoice::where('series', $inv->prefix)->max('number');
if(isset($series) && strlen($series) > 0){
$series += 1;
} else {
$series = 1;
}
$inv->number = $series;
Now the problem is when two users tries to generate invoice for same series at a time it give me duplication error as number column in my table is unique.
Can i do something like
do{
$series = Invoice::where('series', $inv->prefix)->max('number');
if(isset($series) && strlen($series) > 0){
$series += 1;
} else {
$series = 1;
}
$inv->number = $series;
} while($inv->save())
Can anyone help me here. If i get duplicate entry exception the code should bring the count again and it should try to save the record again.