Skip to content

Transactions

Implement ShouldExecuteInTransaction to wrap execute() in a database transaction. Works for both sync and queued execution:

php
use Havn\Executable\Contracts\ShouldExecuteInTransaction;

class TransferFunds implements ShouldExecuteInTransaction
{
    use QueueableExecutable;

    public function execute(Account $from, Account $to, int $amount): void
    {
        $from->update([
            "balance" => $from->balance - $amount,
        ]);

        $to->update([
            "balance" => $to->balance + $amount,
        ]);
    }
}

No need to manually wrap in DB::transaction().

To control how many times the transaction is retried on deadlock, add a transactionAttempts property (defaults to 1, a single attempt with no retries on deadlock, matching Laravel's default):

php
class TransferFunds implements ShouldExecuteInTransaction
{
    use QueueableExecutable;

    public int $transactionAttempts = 3;

    public function execute(Account $from, Account $to, int $amount): void
    {
        /* ... */
    }
}