ahsan's avatar
Level 46

How to create reusable for loop with try catch?

here is the code i'm using:

for ($i=0; $i < 2; $i++) {
    try {
        User::create([
            'name' => 'username'
        ]);
        break;
    } catch (\Illuminate\Database\QueryException $e) {
        if ($i == 1) {
            throw $e;
        }
    }
}

but i want to make reusable this code only substitute data in try loop for example:

for ($i=0; $i < 2; $i++) {
    try {
        
        // replace something here
        // all rest of the code should be ignore and resuable

        break;
    } catch (\Illuminate\Database\QueryException $e) {
        if ($i == 1) {
            throw $e;
        }
    }
}

it could be use case something like this:

loop(function() {
    User::create([
        'name' => 'user name'
    ]);
})
0 likes
3 replies
ahsan's avatar
Level 46

i want to use for something else

but how can i convert this into reusable ?

2 likes
ahsan's avatar
ahsan
OP
Best Answer
Level 46

finally, i figured out the solution.

it's working fine for me:

function loop(Closure $callback, $attempts = 2)
{
    for ($currentAttempt = 1; $currentAttempt <= $attempts; $currentAttempt++) {
        try {
            $callback();
            break;
        } catch (\Illuminate\Database\QueryException $e) {
            if ($currentAttempt == 2) {
                throw $e;
            }
        }
    }
}
3 likes

Please or to participate in this conversation.