Hi guys, iam a really new in laravel but i have a question that is making me crazy on my app.
I have different roles and one of them is the super admin. This user is the only one who can delete other users and also super admins. Now, a question arose about what would happen if 2 super admins eliminated each other at the same time. How can this use case be avoided?, have any sense?
That problem is called race condition. Which might give unexpected results.
Usually it's very very very rare to happen. And to avoid that you will have to use corn jobs. But I don't recommend it for such a simple thing like what you mentioned.
If someone is trying yo solve similar problem you could try this. A partner helpme to solve this
public function destroy(DeleteRequest $request, User $user, StatefulGuard $guard)
{
DB::transaction(function () use ($user, $guard) {
$actor = $guard->user();
// We pull the actor and the affected user with a read/write lock to
// avoid race conditions.
$users = User::whereIn('id', [$actor->id, $user->id])
->lockForUpdate()
->get();
$actor = $users->find($actor->id);
// $actor will be null if another user deleted this $actor first
// while we tried to delete another one. We return 401 because
// the $actor doesnt exists now.
if (null == $actor) {
abort(401);
}
$user = $users->find($user->id);
// $user will be null if another user deleted it first so wi will
// return 404.
if (null == $user) {
throw new ModelNotFoundException();
}
// User should be able to delete itself.
if ($user->id == $actor->id) {
abort(403, __('parser.cannot_delete_your_self_as_super_admin'));
}
try {
$guard->setUser($user);
$guard->logout();
$guard->login($actor);
$user->delete();
} catch (\Exception $e) {
abort(403, __('parser.cannot_delete_user'));
}
});
return response()->noContent();
}