Skip to main content

Invoice Numbers with Prefixes: How to Structure DB?

Premium
9:25

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

T
TAPIWA ✓ Link copied!

This is a beautiful explanation. Much appreciated.

G
GrzesiekB ✓ Link copied!

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...

PK
Povilas Korop ✓ Link copied!

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

DB
Dendy B. Sulistyo ✓ Link copied!
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

M
Modestas ✓ Link copied!

With Laravel 11, you need to use:

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

As the syntax has changed

DB
Dendy B. Sulistyo ✓ Link copied!

Thank you, will try it soon

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.