PHPackages                             sheum/laravel-auto-transaction - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. sheum/laravel-auto-transaction

ActiveLibrary[Database &amp; ORM](/categories/database)

sheum/laravel-auto-transaction
==============================

Automatic database transaction management for Laravel applications

v1.0.0(7mo ago)40[2 PRs](https://github.com/mohamadsheam/laravel-auto-transaction/pulls)MITPHPPHP ^8.0CI passing

Since Oct 5Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/mohamadsheam/laravel-auto-transaction)[ Packagist](https://packagist.org/packages/sheum/laravel-auto-transaction)[ RSS](/packages/sheum-laravel-auto-transaction/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (7)Versions (4)Used By (0)

Laravel Auto Transaction
========================

[](#laravel-auto-transaction)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3a7f9dd5d48085398a78d856fb5001d2d67a3745f56abd6f98ea1497c08774ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736865756d2f6c61726176656c2d6175746f2d7472616e73616374696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sheum/laravel-auto-transaction) [![Total Downloads](https://camo.githubusercontent.com/caeecb4789579bfeae449cac800c6852c916b513cf0e3989f3e3566dca73229d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736865756d2f6c61726176656c2d6175746f2d7472616e73616374696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sheum/laravel-auto-transaction) [![GitHub Tests Action Status](https://camo.githubusercontent.com/da2eac08154e6597ec816ae1faddf26b3114685e8642f63384426e79e656daad/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6f68616d6164736865616d2f6c61726176656c2d6175746f2d7472616e73616374696f6e2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://github.com/mohamadsheam/laravel-auto-transaction/actions)

Automatic database transaction management for Laravel applications. No more manually calling `DB::beginTransaction()`, `DB::commit()`, and `DB::rollBack()`!

Features
--------

[](#features)

- 🛡️ **Middleware support** - Automatic transactions for entire routes
- 🔧 **Trait integration** - Easy to use in services and repositories
- 🎨 **Helper functions** - Simple wrapper functions
- 🔄 **Retry mechanism** - Handle deadlocks automatically
- 🎛️ **Multiple connections** - Support for different database connections

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x or higher

Installation
------------

[](#installation)

```
composer require sheum/laravel-auto-transaction
```

The package will automatically register itself.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=auto-transaction-config
```

Usage
-----

[](#usage)

### Method 1: Using Trait with runInTransaction (Recommended for Services)

[](#method-1-using-trait-with-runintransaction-recommended-for-services)

```
use Sheum\AutoTransaction\Traits\HandlesTransactions;

class UserService
{
    use HandlesTransactions;

    public function createUser(array $data)
    {
        return $this->runInTransaction(function () use ($data) {
            $user = User::create($data);
            $user->profile()->create($data['profile']);

            // Automatically commits on success
            // Automatically rolls back on exception
            return $user;
        });
    }

    public function updateUserWithRetry(User $user, array $data)
    {
        return $this->runInTransaction(
            callback: fn() => $user->update($data),
            attempts: 3,
            connection: 'mysql'
        );
    }
}
```

### Method 2: Using Middleware (For Controllers)

[](#method-2-using-middleware-for-controllers)

Apply to specific routes:

```
// In routes/web.php or routes/api.php
Route::middleware(['transaction'])->group(function () {
    Route::post('/orders', [OrderController::class, 'store']);
    Route::put('/orders/{order}', [OrderController::class, 'update']);
    Route::delete('/orders/{order}', [OrderController::class, 'destroy']);
});

// Or on a single route
Route::post('/users', [UserController::class, 'store'])
    ->middleware('transaction');

// With custom connection
Route::post('/reports', [ReportController::class, 'generate'])
    ->middleware('transaction:reporting_db');
```

Apply to controller methods:

```
class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('transaction')->only(['store', 'update', 'destroy']);
    }

    public function store(Request $request)
    {
        $order = Order::create($request->validated());
        // Automatically commits on successful response (2xx)
        // Automatically rolls back on error or exception
        return response()->json($order, 201);
    }
}
```

### Method 3: Using Helper Functions

[](#method-3-using-helper-functions)

```
// Simple usage
$user = transactional(function () use ($data) {
    $user = User::create($data);
    $user->profile()->create($data['profile']);
    return $user;
});

// With retry attempts
$order = transactional(function () use ($orderData) {
    return Order::create($orderData);
}, attempts: 3);

// With custom connection
$report = transactional(function () use ($data) {
    return Report::create($data);
}, connection: 'reporting_db');

// Using auto_transaction helper
$result = auto_transaction(function () {
    // Your database operations
}, [
    'attempts' => 3,
    'connection' => 'mysql'
]);
```

### Method 4: Using Attributes (Advanced)

[](#method-4-using-attributes-advanced)

For advanced usage, you can use attributes with the trait:

```
use Sheum\AutoTransaction\Attributes\Transactional;
use Sheum\AutoTransaction\Traits\HandlesTransactions;

class OrderService
{
    use HandlesTransactions;

    public function placeOrder(array $orderData)
    {
        return $this->executeWithTransactionIfNeeded('placeOrderWithTransaction', [$orderData]);
    }

    #[Transactional(attempts: 3)]
    protected function placeOrderWithTransaction(array $orderData)
    {
        $order = Order::create($orderData);

        foreach ($orderData['items'] as $item) {
            $order->items()->create($item);
        }

        return $order;
    }
}
```

Configuration Options
---------------------

[](#configuration-options)

### runInTransaction Parameters

[](#runintransaction-parameters)

```
$this->runInTransaction(
    callback: fn() => /* your code */,
    connection: 'mysql',      // Database connection name (default: null)
    attempts: 3,              // Number of retry attempts (default: 1)
    throwOnFailure: true      // Throw exception on failure (default: true)
);
```

### Attribute Parameters

[](#attribute-parameters)

```
#[Transactional(
    connection: 'mysql',      // Database connection name (default: null)
    attempts: 3,              // Number of retry attempts (default: 1)
    throwOnFailure: true      // Throw exception on failure (default: true)
)]
```

Best Practices
--------------

[](#best-practices)

1. **Use `runInTransaction()` for service methods** - Clean and explicit
2. **Use middleware for API endpoints** - Automatic transaction per request
3. **Use helper functions for quick operations** - Simple and straightforward
4. **Use traits in repositories** - Consistent transaction handling
5. **Handle nested transactions carefully** - Laravel uses savepoints
6. **Don't mix transaction methods** - Choose one approach per layer

Error Handling
--------------

[](#error-handling)

The package throws `TransactionException` on failure:

```
use Sheum\AutoTransaction\Exceptions\TransactionException;

try {
    $user = $userService->createUser($data);
} catch (TransactionException $e) {
    Log::error('User creation failed: ' . $e->getMessage());
    return response()->json(['error' => 'Failed to create user'], 500);
}
```

Testing
-------

[](#testing)

```
composer test
```

Examples
--------

[](#examples)

### E-commerce Order Processing

[](#e-commerce-order-processing)

```
use Sheum\AutoTransaction\Traits\HandlesTransactions;

class OrderService
{
    use HandlesTransactions;

    public function completeOrder(Cart $cart, array $paymentData)
    {
        return $this->runInTransaction(function () use ($cart, $paymentData) {
            // Create order
            $order = Order::create([
                'user_id' => $cart->user_id,
                'total' => $cart->total,
            ]);

            // Transfer cart items to order
            foreach ($cart->items as $item) {
                $order->items()->create([
                    'product_id' => $item->product_id,
                    'quantity' => $item->quantity,
                    'price' => $item->price,
                ]);
            }

            // Reduce inventory
            foreach ($cart->items as $item) {
                Product::find($item->product_id)
                    ->decrement('stock', $item->quantity);
            }

            // Process payment
            $payment = Payment::create([
                'order_id' => $order->id,
                'amount' => $cart->total,
                'method' => $paymentData['method'],
            ]);

            // Clear cart
            $cart->items()->delete();

            // All or nothing - automatic commit/rollback
            return $order;
        }, attempts: 3);
    }
}
```

### User Registration with Profile

[](#user-registration-with-profile)

```
use Sheum\AutoTransaction\Traits\HandlesTransactions;

class UserService
{
    use HandlesTransactions;

    public function registerUser(array $data)
    {
        return $this->runInTransaction(function () use ($data) {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);

            $user->profile()->create([
                'bio' => $data['bio'],
                'avatar' => $data['avatar'],
            ]);

            $user->settings()->create([
                'notifications' => true,
                'newsletter' => $data['newsletter'] ?? false,
            ]);

            return $user;
        });
    }
}
```

### Banking Transfer Service

[](#banking-transfer-service)

```
use Sheum\AutoTransaction\Traits\HandlesTransactions;

class BankingService
{
    use HandlesTransactions;

    public function transfer(Account $from, Account $to, float $amount)
    {
        return $this->runInTransaction(
            callback: function () use ($from, $to, $amount) {
                if ($from->balance < $amount) {
                    throw new \Exception('Insufficient funds');
                }

                $from->decrement('balance', $amount);
                $to->increment('balance', $amount);

                return Transaction::create([
                    'from_account_id' => $from->id,
                    'to_account_id' => $to->id,
                    'amount' => $amount,
                ]);
            },
            attempts: 5,
            connection: 'banking'
        );
    }
}
```

Additional Examples
-------------------

[](#additional-examples)

Please see [Additional Examples](EXAMPLES.MD) for more examples.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Credits
-------

[](#credits)

- [MD Nazmul Hasan Sheum](https://github.com/mohamadsheam)

Support
-------

[](#support)

If you discover any issues, please email  or create an issue on GitHub.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance68

Regular maintenance activity

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

220d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/41a18d4e202f575779acc6777dab69c5d9c84f163ae8937bc0531db3a1b6bb8d?d=identicon)[mohamadsheam](/maintainers/mohamadsheam)

---

Top Contributors

[![mohamadsheam](https://avatars.githubusercontent.com/u/13189814?v=4)](https://github.com/mohamadsheam "mohamadsheam (2 commits)")

---

Tags

db-transactionslaravellaravel-packagephplaraveldatabasetransactionrollbackauto-commit

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/sheum-laravel-auto-transaction/health.svg)

```
[![Health](https://phpackages.com/badges/sheum-laravel-auto-transaction/health.svg)](https://phpackages.com/packages/sheum-laravel-auto-transaction)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[mvanduijker/laravel-transactional-model-events

Add eloquent model events fired after a transaction is committed or rolled back

75164.5k](/packages/mvanduijker-laravel-transactional-model-events)[ntanduy/cloudflare-d1-database

Easy configuration and setup for D1 Database connections in Laravel.

215.4k](/packages/ntanduy-cloudflare-d1-database)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
