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? (36 h 00 min)

You also get:

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

Already a member? Login here

TAPIWA avatar

This is a beautiful explanation. Much appreciated.

GrzesiekB 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
Povilas Korop avatar

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

Dendy B. Sulistyo 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

Modestas avatar

With Laravel 11, you need to use:

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

As the syntax has changed

Dendy B. Sulistyo avatar

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.