Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hcastillo's avatar

2 super admins deleted at the same?

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?

0 likes
5 replies
MohamedTammam's avatar

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.

1 like
hcastillo's avatar

@MohamedTammam Thank you for the answer. Do you thing that using 'Pessimistic Locking' from DB could help to solve the problem too?

MohamedTammam's avatar

@hcastillo IMO, it depends on your app and how danger it is and how you manage it from front-end and back-end. It depends on the case.

1 like
hcastillo's avatar

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();
}

Please or to participate in this conversation.