How to access attempt number from inside Laravel DB Transaction?

Viewed 92

This is a simplified version of what I'm planning to do,

This Transaction is set to retry 5 times for example.

How can I access the attempt number from inside transaction?

DB::transaction(function ()
{
    $number = 1;

    if($ATTEMPT_NUMBER > 1){ // <-- How do I know attempt number? (e.g. #2 of 5 attempts)
         $number += $ATTEMPT_NUMBER;
    }

    DB::update("update table set something = {$number}");

    //... other DB stuff here

}, 5); // <-- 5 Attempts

I've tried:

$counter = 0;
DB::transaction(function () use ($counter)
{
    $number = 1 + $counter++;

    DB::update("update table set something = {$number}");

}, 5);

But it doesn't work.

1 Answers

Your question looks like an XY problem and it would be useful to let us know what you are trying to achieve in case there's a better way to do it:

Broadly speaking if you want to modify a variable that is useed in the scope of a callback you need to use it by refrence:

$counter = 0;
DB::transaction(function () use (&$counter)
{
    $number = 1 + $counter++;
    DB::update("update table set something = {$number}");
}, 5);

However keep in mind since this is happening within a failing transaction the update will not actially "stick" until the transaction succeeds.

Related