Transactions

Laravel Service-Layer Transaction

Coordinates a stock adjustment inside a database transaction while keeping HTTP concerns outside the domain operation.

PHP Laravel Advanced

Problem

Engineering context

Inventory updates often span validation, stock movement and audit state that must succeed or fail together.

Solution boundary

Use an application service to coordinate the invariant inside one transaction.

app/Services/InventoryService.phpPHP
<?php

final class InventoryService
{
    public function adjustStock(Product $product, int $quantity): void
    {
        DB::transaction(function () use ($product, $quantity): void {
            $product->adjustQuantity($quantity);
            StockMovement::record($product, $quantity);
        });
    }
}

How it works

How it works

The service owns orchestration while the model remains responsible for domain state.

Security considerations

Security considerations

Authorization must be completed before invoking the service, and tenant ownership must be verified inside the same trusted boundary.

Performance considerations

Performance considerations

Keep transaction scope small and lock only rows participating in the invariant.

Tradeoffs

Tradeoffs

A service layer adds a type and dependency but makes the transaction boundary explicit.

Testing notes

Testing notes

Feature-test authorization and rollback; unit-test quantity rules.

Limitations

Limitations

Illustrative public-safe example; adapt the boundary and domain rules to the actual application.

Continue exploring

Related examples

Engineering insights

Practical notes, occasionally.

Double opt-in, no list selling, and unsubscribe anytime.