title: Generate Unique Serial Number for invoice for a particular companies Php - Laravel
body: <p>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</p>
  
  <pre><code>id | company_id | series |  number | amount
  </code></pre>
  
  <p>Now to generate invoice number what I do is; for a particular company take count and add 1 to that.</p>
  
  <pre><code>//assume $inv-&gt;prefix is a string which gives me series for particular company.
  $series = Invoice::where('series', $inv-&gt;prefix)-&gt;max('number');
  if(isset($series) &amp;&amp; strlen($series) &gt; 0){
      $series += 1; 
  } else {
      $series = 1;
  }
  $inv-&gt;number = $series;
  </code></pre>
  
  <p>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.</p>
  
  <p>Can i do something like</p>
  
  <pre><code>do{
      $series = Invoice::where('series', $inv-&gt;prefix)-&gt;max('number');
      if(isset($series) &amp;&amp; strlen($series) &gt; 0){
          $series += 1; 
      } else {
          $series = 1;
      }
      $inv-&gt;number = $series;
  } while($inv-&gt;save())
  </code></pre>
  
  <p>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.</p>