Level 46
Why not use a factory?
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'
]);
})
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;
}
}
}
}
Please or to participate in this conversation.