Courses

How to Structure Databases in Laravel

Invoice Numbers with Prefixes: How to Structure DB?

Previous: Recursive Parent-Children - Part 2: Nested Set Model with Package
avatar

This is a beautiful explanation. Much appreciated.

avatar
You can use Markdown
avatar

Isn't it better to use the observer when adding an invoice? If the invoice number is NULL then generate a sequential number. In observer you can use the updating method...

👍 1
avatar

Yes that's one of the options. It's a personal preference on where to perform that calculation, observer or elsewhere.

avatar
You can use Markdown
avatar
public function getFullInvoiceNumberAttribute()
{
    return 'ABC-' . str_pad($this->id, 5, '0', STR_PAD_LEFT);
}

public function setInvoiceNumberAttribute()
{
    $this->attributes['invoice_number'] = App\Models\Invoice::max('invoice_number') + 1;
}

in Laravel 11,

App\Models\Invoice::create(['user_id' => 1, 'paid_total' => 200, 'invoice_number' => 0]); = App\Models\Invoice {#6539 user_id: 1, paid_total: 200, invoice_number: 0, updated_at: "2024-07-22 22:11:33", created_at: "2024-07-22 22:11:33", id: 5, } why invoice_number still 0 ? t

avatar

With Laravel 11, you need to use:

https://laravel.com/docs/11.x/eloquent-mutators#accessors-and-mutators

As the syntax has changed

avatar

Thank you, will try it soon

avatar
You can use Markdown
avatar
You can use Markdown