skip to Main Content

I have an app with invoices, I set the invoice id to auto-increment.

my client wants the ID to include the year and restart at 1 when a year passes. for instance ids could look like this.

2023-344
2023-345
2023-346
etc…
until we reach 2024 in which case the next id would be
2024-1

I’ve never attempted to customize the id column in mysql and I am not sure how a change like this could affect the indexing speed. I am wondering what the best way to handle this would be.

my app is in laravel and my database is in mysql

2

Answers


  1. You can add seperated column invoice_id. And can write new method in your model:

    Schema::create('invoices', function (Blueprint $table) {
       $table->string('invoice_id');
       $table->index('invoice_id');
    });
    
    public static function createNewInvoice() {
        $currentYear = now()->year;
        $lastInvoice = Invoice::where('year', $currentYear)->orderBy('number', 'desc')->first();
        $number = $lastInvoice ? $lastInvoice->number + 1 : 1;
    
        $invoice = new Invoice();
        $invoice->year = $currentYear;
        $invoice->number = $number;
        $invoice->save();
    
        return $invoice;
    }
    

    You can modify method as you want.

    Login or Signup to reply.
  2. First of all, you CAN ONLY use auto_increment on INT or BIGINT fields, you can’t use "-" or any other characters.

    I don’t know how the model layer in Laravel works, but you can alter the MySQL table and add a Generated Column. Explantion here.

    Maybe you can have something like this:

    CREATE TABLE t1 (c1 INT);
    ALTER TABLE t1 ADD COLUMN c2 INT GENERATED ALWAYS AS YEAR(CURRENT_DATE()) + "-" + ID_sequence;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search