moe-mizrak / transaction-builder
TransactionBuilder
Installs: 1
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
Open Issues: 0
Type:package
Requires
- php: ^8.2
Requires (Dev)
- ext-pdo: *
- fakerphp/faker: ^1.24.1
- laravel/pint: ^1.22
- orchestra/testbench: ^9.6.1
- phpunit/phpunit: ^11.4
This package is not auto-updated.
Last update: 2025-05-06 18:43:53 UTC
README
A lightweight fluent wrapper around Laravel DB::transaction()
with support for retries, on-failure callbacks, and result access.
Installation
composer require moe-mizrak/transaction-builder
Methods
make()
: Create a new instance of the TransactionBuilder.attempts(int $attempts)
: The number of attempts to run the transaction. - default is 1.run(callable $callback)
: The callback to be executed within the transaction.onFailure(callable $callback)
: The callback to be executed if the transaction fails after all attempts.disableThrow()
: Disable throwing exceptions on failure. - default is false (meaning that exceptions will be thrown as usual).result()
: Get the result of the transaction. If the transaction fails, it will return null ifdisableThrow()
is called, or throw an exception otherwise.
Usage
$result = TransactionBuilder::make() ->attempts(3) // number of attempts ->run(function () { // your transaction logic return 'done'; }) ->result();
On Failure Callback
$result = TransactionBuilder::make() ->run(function () { throw new \Exception("fail"); }) ->onFailure(function ($exception) { logger()->error($exception->getMessage()); }) ->disableThrow() // optional if you want to disable throwing exceptions since you already have onFailure callback ->result();
Nested Transactions
$result = TransactionBuilder::make() ->run(function () { // outer transaction logic TransactionBuilder::make() ->attempts(2) // number of attempts ->run(function () { // inner transaction logic }) ->onFailure(function ($exception) { logger()->error($exception->getMessage()); }) ->result(); }) ->result();
You can also do this:
$result = TransactionBuilder::make() ->run(function () { // outer transaction logic DB::transaction(function () { // inner transaction logic }); }) ->result();
💫 Contributing
Your contributions are welcome! If you'd like to improve this package, simply create a pull request with your changes. Your efforts help enhance its functionality and documentation.
If you find this package useful, please consider ⭐ it to show your support!
📜 License
Transaction Builder for Laravel is an open-sourced software licensed under the MIT license.