PHPackages                             niclas-van-eyk/laravel-transactional-controllers - 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. niclas-van-eyk/laravel-transactional-controllers

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

niclas-van-eyk/laravel-transactional-controllers
================================================

Effortlessly wrap your controller actions with database transactions.

v0.2.1(2y ago)51.1k1[3 PRs](https://github.com/NiclasvanEyk/laravel-transactional-controllers/pulls)MITPHPPHP ^8.1

Since May 21Pushed 2y ago1 watchersCompare

[ Source](https://github.com/NiclasvanEyk/laravel-transactional-controllers)[ Packagist](https://packagist.org/packages/niclas-van-eyk/laravel-transactional-controllers)[ Docs](https://github.com/niclas-van-eyk/laravel-transactional-controllers)[ GitHub Sponsors](https://github.com/NiclasvanEyk)[ RSS](/packages/niclas-van-eyk-laravel-transactional-controllers/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (11)Versions (8)Used By (0)

`#[Transactional]` Laravel Controllers
======================================

[](#transactional-laravel-controllers)

Effortlessly wrap your controller actions with database transactions.

[![Latest Version on Packagist](https://camo.githubusercontent.com/ca2227e5a3c1e1d81edac474e9950117ce3770360080142b06092312be44d797/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e69636c61732d76616e2d65796b2f6c61726176656c2d7472616e73616374696f6e616c2d636f6e74726f6c6c6572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/niclas-van-eyk/laravel-transactional-controllers)[![Total Downloads](https://camo.githubusercontent.com/d820f76a0aa74a58699401201481a0b92bf88452f44b7f00619ad3231dc62dfb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e69636c61732d76616e2d65796b2f6c61726176656c2d7472616e73616374696f6e616c2d636f6e74726f6c6c6572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/niclas-van-eyk/laravel-transactional-controllers)

```
class ExampleUsageController
{
    #[Transactional]
    public function demo(Request $request)
    {
        User::create($request->all());
        User::create($request->all());

        throw new Exception("Everything will be rolled back!");
    }
}
```

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

[](#installation)

You can install the package via composer:

```
composer require niclas-van-eyk/laravel-transactional-controllers
```

Background
----------

[](#background)

If you want to make a series of edits to your database, where either *all* should happen at once, or *none at all*, you typically use database transactions. The example we use here is a user (`$author`) transferring a certain `$amount` of to another user (`$receiver`). We also want to save that the fact that this transfer took place in a separate model (`TransferLog`).

Usage
-----

[](#usage)

Before you might have written something like this:

```
namespace App\Http\Controllers;

use App\Http\Requests\TransferMoneyRequest;
use App\Models\TransferLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BankAccountController
{
    public function transferMoney(TransferMoneyRequest $request)
    {
        return DB::transaction(function () use ($request) {
            $request->author->balance->decrement($request->amount);
            $request->receiver->balance->increment($request->amount);

            return TransferLog::createFromTransferRequest($request);
        })
    }
}
```

You have to wrap your whole code inside one big closure, explicitly `use` all parameters you inject, and if you want to return something from *inside* the transaction closure, you end up with this double return, making the code harder to read and your IDE angry.

`laravel-transactional-controllers` solves this, by eliminating the need to wrap the code inside a closure and instead adding the `Transactional` attribute to the controller method:

```
namespace App\Http\Controllers;

use App\Http\Requests\TransferMoneyRequest;
use App\Models\TransferLog;
use Illuminate\Http\Request;
use NiclasVanEyk\TransactionalControllers\Transactional; // author->balance->decrement($request->amount);
        $request->receiver->balance->increment($request->amount);

        return TransferLog::createFromTransferRequest($request);
    }
}
```

No more `use`, double `return`s or your IDE complaining about it not being able to guarantee a correct return type!

You can also explicitly specify the database connection to use for running the transaction (`config('database.default')` is used by default):

```
    #[Transactional(connection: 'other')]
    public function store() {}
```

Limitations
-----------

[](#limitations)

This only works when using controllers:

```
use NiclasVanEyk\TransactionalControllers\Transactional;

// Works ✅
class RegularController
{
    #[Transactional]
    public function store() {}
}
Route::post('/regular-store', [RegularController::class, 'store']);

// Works ✅
class InvokableController
{
    #[Transactional]
    public function __invoke() {}
}
Route::post('/invokable-store', InvokableController::class);

// Does not work ❌
Route::post(
    '/invokable-store',
    #[Transactional]
    function () { /* Will not open a transaction! */},
)
```

Implementation Details
----------------------

[](#implementation-details)

This package uses Laravels [`ControllerDispatcher`](https://github.com/laravel/framework/blob/master/src/Illuminate/Routing/Contracts/ControllerDispatcher.php) component, which determines how the controller action should be executed. This means we can defer opening a transaction until the last possible moment, preventing **unnecessary transactions from being opened**! If e.g. the validation inside a `FormRequest` fails, or a model is not found when using route model binding, no transaction is started.

Changelog
---------

[](#changelog)

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

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

[](#contributing)

If you have any ideas for changes, feel free to open issues, PRs or fork the project.

### Local Development

[](#local-development)

This assumes you already have installed sqlite, PHP, and all composer dependencies locally.

Run tests

```
composer test
```

Run formatter

```
composer fix-cs
```

Run analysis

```
composer analyse
```

Run all of the above at once

```
composer ci
```

Credits
-------

[](#credits)

- [Niclas van Eyk](https://github.com/niclas-van-eyk)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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

Every ~247 days

Total

3

Last Release

957d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9ab82eb06e71c1e4ffd35530565c0a705598483a617d240616c7771e4e736533?d=identicon)[NiclasvanEyk](/maintainers/NiclasvanEyk)

---

Top Contributors

[![NiclasvanEyk](https://avatars.githubusercontent.com/u/10284694?v=4)](https://github.com/NiclasvanEyk "NiclasvanEyk (9 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (7 commits)")

---

Tags

laraveldatabasetransactionsniclas-van-eyk

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/niclas-van-eyk-laravel-transactional-controllers/health.svg)

```
[![Health](https://phpackages.com/badges/niclas-van-eyk-laravel-transactional-controllers/health.svg)](https://phpackages.com/packages/niclas-van-eyk-laravel-transactional-controllers)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[guidocella/eloquent-populator

Guess attributes for Eloquent model factories

7661.6k2](/packages/guidocella-eloquent-populator)[ntanduy/cloudflare-d1-database

Easy configuration and setup for D1 Database connections in Laravel.

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

PHPackages © 2026

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