Auto increment bill number logic for Laravel

Auto increment bill number logic for Laravel

If you are searching on how to generate invoice or bill number, welcome to my blog ?. Today, I am going to show you how you can generate dynamic invoice number. Please note, this might not be the best solution but this works pretty well. I have been using this way on various project, it is working fine.

Let’s move to your model first. Let’s assume, you have a model Invoice. Inside that model, add following lines of code. boot() basically, is called before you save datas to database. So you can make some variable value assign before saving it to the database.

I have introduced 2 tables for this to work. And they are as follows:

  1. Invoice table
  2. Prefix table

From above diagram, I hope you are cleared how they are connected. From backend, admin adds new prefix with active status. Make sure, there is only one row with active = true else it might create some serious issue.

In Invoice table, number columns is incrementing based on prefix_id. If the table finds new prefix_id, it will start adding number starting from 1. This might be helpful to reset bill number to start from 001. This is also helpful, if reset starting number of bill for new fiscal year.

Now, let’s see the code how we can achieve this. Here is the code which you should include in your Invoice model.

public static function boot()

    static::creating(function ($invoice) {
        $current_prefix = $get_active_prefix_model;
        $invoice->number = Invoice::where('prefix_id', $current_prefix->id)->max('number') + 1;

        $invoice->bill_number = $current_prefix->name . '-' . str_pad(
            5, // as per your requirement.

The code is written based on database structure mentioned above. Let me explain you one by one.

  • $current_prefix = $get_active_prefix_model;
    • Get prefix model with active = true.
  • $invoice->number = Invoice::where('prefix_id', $current_prefix->id)->max('number') + 1;
    • Get max value from column number where prefix_id is the one with active = true in prefix table.
    • This way you will get max number of invoice for specific prefix.
    • Lastly, add 1 to increment invoice number for next invoice.
  • $invoice->bill_number = $current_prefix->name . '-' . str_pad($invoice->number,5, '0',STR_PAD_LEFT);
    • Get current active prefix name
    • Append '-'
    • Append number to get invoice number like this 00001.
  • As a result
    • You will get invoice number as prefix1-00001

And it’s done. Now you can generate invoice number which automatically increases based on prefix set.

I hope this will help you in bill generating application. If yes, let me know. And if there is any issue or didn’t understand, let me know too. As always, if you liked it, I appreciate if you would share my blog else no problem ?.


Leave a Reply