php 98 lines · 3 tabs

Laravel database transactions for data integrity

Carlos Mendez Jan 2026
3 tabs
<?php

use Illuminate\Support\Facades\DB;

public function createOrder(array $items, User $user)
{
    return DB::transaction(function () use ($items, $user) {
        // Create order
        $order = Order::create([
            'user_id' => $user->id,
            'total' => 0,
        ]);

        $total = 0;

        foreach ($items as $item) {
            // Create order items
            $orderItem = $order->items()->create([
                'product_id' => $item['product_id'],
                'quantity' => $item['quantity'],
                'price' => $item['price'],
            ]);

            // Update inventory
            $product = Product::findOrFail($item['product_id']);

            if ($product->stock < $item['quantity']) {
                throw new \Exception("Insufficient stock for {$product->name}");
            }

            $product->decrement('stock', $item['quantity']);

            $total += $item['price'] * $item['quantity'];
        }

        // Update order total
        $order->update(['total' => $total]);

        return $order;
    }, 3); // Retry 3 times on deadlock
}
3 files · php Explain with highlit

Database transactions ensure multiple database operations succeed or fail together, maintaining data consistency. I wrap related operations in DB::transaction() which automatically commits on success and rolls back on exceptions. For manual control, I use DB::beginTransaction(), DB::commit(), and DB::rollBack(). Nested transactions use savepoints internally. The transaction closure receives attempts count for retry logic. Eloquent events fire after transactions commit when using $afterCommit property. For distributed transactions across services, I implement saga patterns. Transactions prevent partial updates that leave data in inconsistent states—critical for payment processing, inventory management, or multi-table updates. Proper transaction usage is fundamental to data integrity.


Related snips

ruby
timestamp = request.headers.fetch('X-Signature-Timestamp')
signature = request.headers.fetch('X-Signature')
payload = request.raw_post

data = "#{timestamp}.#{payload}"
expected = OpenSSL::HMAC.hexdigest('SHA256', ENV.fetch('WEBHOOK_SECRET'), data)

HMAC signed API requests for webhook and partner integrity

hmac api-signing webhooks
by Kai Nakamura 2 tabs
go
package dbutil

import (
  "context"

  "github.com/jackc/pgconn"

Retry Postgres serialization failures with bounded attempts

go postgres transactions
by Leah Thompson 1 tab
ruby
class SignupForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :account_name, :string
  attribute :email, :string

Shallow Controller, Deep Params: Form Object Pattern

rails activemodel form-object
by codesnips 3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first

SQL injection prevention with unsafe and safe query patterns

sql-injection owasp database
by Kai Nakamura 3 tabs
php
<?php

namespace App\Providers;

use App\Contracts\PaymentGateway;
use App\Services\StripePaymentGateway;

Laravel service container and dependency injection

laravel dependency-injection service-container
by Carlos Mendez 2 tabs
sql
-- EXPLAIN ANALYZE (actual execution statistics)
EXPLAIN ANALYZE
SELECT u.username, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2024-01-01'

Advanced query optimization techniques

database optimization query-performance
by Maria Garcia 2 tabs

Share this code

Here's the card — post it anywhere.

Laravel database transactions for data integrity — share card
Link copied