Courses

Structuring Databases in Laravel 11

Invoice Numbers with Series Prefixes

Summary of this lesson:
- Structuring invoice number systems
- Managing auto-incrementing prefixes
- Implementing custom number formats
- Handling user-specific numbering

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 18 lessons of this course? (81 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord