Livewire Invoice Line Items: Add and Remove Rows With Live Totals (and Why the Wrong Row Gets Deleted)
Livewire Invoice Line Items: Add and Remove Rows With Live Totals (and Why the Wrong Row Gets Deleted)
An invoice form where you can add a row, remove a row, type a quantity and price, and see the subtotal and tax update looks like a 20-minute job in Livewire. In practice it is where a lot of Livewire questions come from: totals that don't update, totals that keep growing, and the classic one, where you click "remove" on row 1 and the inputs of row 2 now show the wrong values.
This checklist builds the editor in a way that avoids those problems. The code is written for Livewire v3 (attribute syntax such as #[Computed]), Laravel 10+ and PHP 8.2+.
1. Keep each line as one row in one array
A common first attempt uses parallel arrays: qty.0, price.0, name.0, qty.1, … That makes adding, removing and summing rows painful, because every operation has to touch several arrays and keep them in sync.
Use one array where each element is a complete line:
public array $lines = [
// 'l01jab...' => ['description' => '', 'quantity' => '1', 'unit_price' => '0.00', 'taxable' => true],
];
Each line then has everything needed to compute its own total, and the invoice total is a simple loop over $lines.
2. Give every row a stable ID and use it everywhere
Livewire's documentation says that inside a @foreach loop "you must add a unique wire:key attribute to the root element rendered by the loop", otherwise it cannot match old elements to new ones between requests.
The less obvious part is that wire:key, wire:model and wire:click must all address the row the same way. A Livewire maintainer explained this in a GitHub discussion: when wire:key uses the row's ID but wire:model="lines.{{ $index }}.quantity" and wire:click="remove({{ $index }})" use the array index, re-indexing the array with array_values() after a delete shifts the indexes while the keyed elements are preserved. The inputs and remove buttons can then point at the wrong rows.
Two consistent options exist:
- Index everywhere:
wire:key="{{ $index }}",wire:model="lines.{{ $index }}…",remove({{ $index }}), and re-index after delete. - ID everywhere (used below): store rows in an associative array keyed by a stable ID, use that ID for the key, the model path and the action, and simply
unset()the row without re-indexing.
The second option keeps a row's DOM element, focus and any attached JavaScript with the row you think it belongs to.
Note: the GitHub report was filed against Livewire 4.1.3. The explanation is about how keys and model paths relate, so the same rule is a safe default on Livewire 3, but test delete-in-the-middle on your version.
Use a non-numeric string key (for example a prefix plus a ULID), so the ID can never be mistaken for a position in the array.
3. Add and remove rows
<?php
namespace App\Livewire;
use App\Support\InvoiceMath;
use Illuminate\Support\Str;
use Livewire\Attributes\Computed;
use Livewire\Component;
class InvoiceLines extends Component
{
/** @var array<string, array{description: string, quantity: string, unit_price: string, taxable: bool}> */
public array $lines = [];
public string $taxRate = '20';
public bool $taxInclusive = false;
public function mount(): void
{
$this->addLine();
}
public function addLine(): void
{
$id = 'l' . Str::lower((string) Str::ulid());
$this->lines[$id] = [
'description' => '',
'quantity' => '1',
'unit_price' => '0.00',
'taxable' => true,
];
}
public function removeLine(string $id): void
{
unset($this->lines[$id]);
if ($this->lines === []) {
$this->addLine(); // keep one empty row so the form never disappears
}
}
#[Computed]
public function totals(): array
{
return InvoiceMath::summarize($this->lines, (float) $this->taxRate, $this->taxInclusive);
}
public function render()
{
return view('livewire.invoice-lines');
}
}
And the Blade view:
<div>
<table>
@foreach ($lines as $id => $line)
<tr wire:key="line-{{ $id }}">
<td><input type="text" wire:model.blur="lines.{{ $id }}.description"></td>
<td><input type="number" min="0" step="any" wire:model.live.debounce.300ms="lines.{{ $id }}.quantity"></td>
<td><input type="number" min="0" step="0.01" wire:model.live.debounce.300ms="lines.{{ $id }}.unit_price"></td>
<td><input type="checkbox" wire:model.live="lines.{{ $id }}.taxable"></td>
<td>{{ number_format(\App\Support\InvoiceMath::lineCents($line) / 100, 2) }}</td>
<td><button type="button" wire:click="removeLine('{{ $id }}')">Remove</button></td>
</tr>
@endforeach
</table>
<button type="button" wire:click="addLine">Add line</button>
<dl>
<dt>Net</dt><dd>{{ number_format($this->totals['net'] / 100, 2) }}</dd>
<dt>Tax</dt><dd>{{ number_format($this->totals['tax'] / 100, 2) }}</dd>
<dt>Total</dt><dd>{{ number_format($this->totals['total'] / 100, 2) }}</dd>
</dl>
</div>
type="button" on the buttons matters if the table sits inside a <form wire:submit>: a plain <button> inside a form submits it.
4. Make the totals actually update
If the subtotal only changes when you click a button, check the binding. In Livewire 3, plain wire:model is deferred: the documentation says Livewire "will only send a network request when an action is performed (like wire:click or wire:submit), NOT when a wire:model input is updated".
- Use
wire:model.livefor fields that drive the totals (quantity, price, the taxable checkbox). By default.liveadds a 150 ms debounce;.live.debounce.300mswaits a little longer while the user types. - Use
wire:model.blurfor text fields such as the description, so typing a long description doesn't send a request per keystroke.
5. Compute totals; don't accumulate them
Another common bug: a calculateTotal() method that does $this->total += … inside an updated hook. Every change adds to the previous value instead of starting from zero, so the total keeps growing.
Derive totals from $lines on every render instead. A #[Computed] method (as above) is a good fit. Livewire's docs point out that computed properties are only cached for a single request, so the value is recalculated after each update and never goes stale between requests.
If you need to react to one field changing (for example, filling the unit price when a product is chosen), use the array form of the updated hook. Livewire passes the changed key as a second argument:
public function updatedLines($value, $key): void
{
// $key looks like "l01jab....unit_price"
[$id, $field] = explode('.', $key, 2) + [null, null];
if ($field === 'quantity' && (float) $value < 0) {
$this->lines[$id]['quantity'] = '0';
}
}
Note: the docs say $key is null when the whole array is replaced instead of a single key, so guard for that case. The docs show a one-level example; dump $key once to confirm the format for nested fields on your version.
6. Do the money math in integer cents
Floats can't represent most decimal amounts exactly. In PHP, 0.1 + 0.2 == 0.3 is false (the sum is 0.30000000000000004). Rounding to 2 decimals at the end usually hides this, but invoices are where "usually" causes trouble. Convert to integer cents once, do all sums in integers, and only format at display time:
<?php
namespace App\Support;
final class InvoiceMath
{
public static function toCents(string|int|float $amount): int
{
return (int) round(((float) $amount) * 100);
}
public static function lineCents(array $line): int
{
return (int) round(((float) ($line['quantity'] ?? 0)) * self::toCents($line['unit_price'] ?? 0));
}
/** @return array{net: int, tax: int, total: int} */
public static function summarize(array $lines, float $ratePercent, bool $inclusive): array
{
$subtotal = 0;
$taxable = 0;
foreach ($lines as $line) {
$cents = self::lineCents($line);
$subtotal += $cents;
if (! empty($line['taxable'])) {
$taxable += $cents;
}
}
$rate = max(0.0, $ratePercent) / 100;
if ($inclusive) {
// Prices already contain tax: extract it.
$tax = (int) round($taxable - $taxable / (1 + $rate));
return ['net' => $subtotal - $tax, 'tax' => $tax, 'total' => $subtotal];
}
// Prices exclude tax: add it on top.
$tax = (int) round($taxable * $rate);
return ['net' => $subtotal, 'tax' => $tax, 'total' => $subtotal + $tax];
}
}
Note: toCents() still goes through a float for the conversion, which is fine for ordinary two-decimal prices. For very large amounts or more than two decimals, parse the string yourself or use a money/decimal library.
7. Tax-inclusive vs tax-exclusive, with numbers
The two modes use different formulas, and mixing them up is a common source of "the total is off by a few cents" reports.
- Tax-exclusive (prices are net):
tax = taxable × rate,total = subtotal + tax. - Tax-inclusive (prices already include tax):
tax = taxable − taxable ÷ (1 + rate),total = subtotal.
Example with a 20% rate: 2 × 49.99 (taxable) and 1 × 15.00 (not taxable). The summarize() function above gives:
| Mode | Net | Tax | Total |
|---|---|---|---|
| Exclusive | 114.98 | 20.00 (19.996 rounded) | 134.98 |
| Inclusive | 98.32 | 16.66 (99.98 − 83.3166…) | 114.98 |
The inclusive tax is not 20% of 99.98. It is the part of 99.98 that is tax: 99.98 ÷ 1.2 = 83.32 net for the taxable lines, so 16.66 is tax. Adding the untaxed 15.00 gives the 98.32 net shown.
Per-line vs per-invoice rounding. Three lines of 0.99 at 7.5%: rounding the tax on each line gives 0.07 × 3 = 0.21; rounding once on the invoice total (2.97 × 7.5% = 0.22275) gives 0.22. Both methods are in use. Which one you must use depends on your jurisdiction and your accounting or tax provider.
Note: this is display math. Rates, exemptions, reverse charge and which rounding rule applies are tax questions. Take them from your tax engine, merchant of record or accountant, not from the UI.
8. Validate and recalculate on the server before saving
Livewire's documentation is explicit: "always treat public properties as user input". Anyone can change $lines, the tax rate or the inclusive flag from the browser's devtools, so:
- Validate the array with wildcard rules before saving:
php
$this->validate([
'lines' => ['required', 'array', 'min:1'],
'lines.*.description' => ['required', 'string', 'max:255'],
'lines.*.quantity' => ['required', 'numeric', 'min:0'],
'lines.*.unit_price' => ['required', 'numeric', 'min:0'],
'lines.*.taxable' => ['boolean'],
]);
- Recompute the totals on the server with the same
InvoiceMathand store those. Never save a total that came from the browser. - Load the tax rate from your own settings or tax service at save time instead of trusting
$taxRate. - If the component holds a record ID (for example
$invoiceId), mark it with#[Locked]so it can't be changed from the client, and still authorize the user against it.
Quick symptom table
| Symptom | Likely cause | Fix |
|---|---|---|
| Removing row 1 makes row 2 show wrong values | wire:key uses an ID but wire:model/wire:click use the index |
Address rows the same way everywhere (step 2) |
| Totals update only after clicking something | Plain wire:model is deferred |
wire:model.live on quantity/price (step 4) |
| Total keeps growing with each edit | += into a stored total |
Computed totals from $lines (step 5) |
| Total off by 0.01 | Float sums or mixed rounding rules | Integer cents; pick one rounding rule (steps 6–7) |
| "Remove" submits the form | <button> inside a form defaults to submit |
type="button" (step 3) |
If you'd rather not build the UI yourself
If you want these pieces ready-made, Billstack ($29) is a set of five Livewire components for billing portals. Its InvoiceLineEditor (add / remove / reorder lines, qty × unit, live subtotal) handles the problem from step 2: since v1.0.1, rows are stored under a stable row key, and wire:key, wire:model, remove, move up and move down all use that key, with no re-indexing after a delete. The product page lists v1.0.1 as fixing invoice lines that showed the wrong values after a row was deleted.
The other four components are a TaxSummary (taxable base, rate, inclusive / exclusive toggle), a PaymentStatusBadge, a filterable CustomerInvoiceTable and RecurringScheduleFields. The package installs as a Composer path repository and comes with Blade views, math helpers, an INSTALL guide, a local demo with fake data and a PHPUnit suite. It is UI only: no Stripe, Paddle or Lemon Squeezy integration, no tax engine or VAT compliance, no PDF or email, no multi-currency and no Filament resources. Listed requirements: PHP 8.2+, Laravel 10+, and Livewire 3 or 4. This article's examples are written for Livewire 3. Its built-in money helpers round to two decimals rather than working in integer cents, so step 8 (validate and recalculate on the server) still applies.
Sources
- Livewire 3 docs, Components — "Adding wire:key to @foreach loops": https://livewire.laravel.com/docs/3.x/components
- Livewire 3 docs, Troubleshooting — component mismatches and wire:key: https://livewire.laravel.com/docs/3.x/troubleshooting
- Livewire discussion #9954, "Input is not set correctly after switching wire:model target" (maintainer answer on key/model addressing): https://github.com/livewire/livewire/discussions/9954
- Livewire 3 docs, wire:model — deferred updates,
.live,.blur, debounce: https://livewire.laravel.com/docs/3.x/wire-model - Livewire 3 docs, Computed properties — cached for a single request: https://livewire.laravel.com/docs/3.x/computed-properties
- Livewire 3 docs, Lifecycle hooks —
updatedhooks for arrays and$key: https://livewire.laravel.com/docs/3.x/lifecycle-hooks - Livewire 3 docs, Properties — security concerns and
#[Locked]: https://livewire.laravel.com/docs/3.x/properties - Laravel docs, Validation — validating nested array input: https://laravel.com/docs/12.x/validation#validating-nested-array-input
- PHP manual, Floating point numbers (precision warning): https://www.php.net/manual/en/language.types.float.php