Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Invoice Numbers with Series Prefixes

Premium
4 min read

In this lesson, let's examine the database structure for invoice numbers. For example, an invoice number can start with a series or prefix and then a number leading with zeros, like INT-001.

Another example could be a year and then 001 after the dash, like 2024-001. Or some word and then the number, like Mars-108.

So, how do you store that in the database and make that incremental?


Eloquent Mutators

Imagine a simplified Invoice table where we save the invoice number in the invoice_number column.

Schema::create('invoices', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->unsignedBigInteger('invoice_number');
$table->integer('paid_total');
$table->timestamps();
});

How do you set the invoice_number column to be incremented when the invoice is created? Probably the easiest way would be to use an Eloquent mutator.

app/Models/Invoice.php:

use Illuminate\Database\Eloquent\Casts\Attribute;
 
class Invoice extends Model
{
protected $fillable = [
'user_id',
'invoice_number',
'paid_total',
];
 
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
 
protected function invoiceNumber(): Attribute
{
return Attribute::make(
set: fn () => Invoice::max('invoice_number') + 1,
);
}
}

The downside of this method is you still need to pass...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

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

Already a member? Login here

Comments & Discussion

No comments yet…