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

anderking's avatar

How do I delete all user records except my current session?

I have a controller function that deletes all users, but when I run it it will delete all users including me (my session) as I do so I delete all except my current session?

public function destroyall()
{
    $id = Auth::user()->id;

    $userexcept = User::find($id);
    $user = User::all();
    $user->each(function($user){
            $user->delete();
    });
    Flash('Users delete','info');
    return redirect()->route('admin.users.index');
}
0 likes
6 replies
edoc's avatar

How bout this?

$users = User::where('id', '!=', auth()->id())->get();

$users->delete();

@anderking

agus24's avatar
agus24
Best Answer
Level 5

this?

$users = User::all()->except(auth()->id())
Prabhakar's avatar
User::where('id', '!=', auth()->id())->delete();
AddWebContribution's avatar

Use this code in your destroyall() method

$id = Auth::user()->id;

$users = User::where('id', '!=', $id)->delete();

Hope this work for you !

MaverickChan's avatar

guys , he wants to delete all the records which do not belong to current user.

  1. provide a model relationship , some hasmany , as a user can have many posts.

  2. delete all the records through model.

Snapey's avatar

What has the User model got to do with sessions?

Deleting users will not kill sessions.

Please or to participate in this conversation.