Laravel - Deleting auth user account while user is logged in

Jack Barham picture Jack Barham · Aug 7, 2014 · Viewed 8.2k times · Source

I'm trying to build a function where a user can delete their own account while they are logged in. I'm struggling to find any example or logic/best practices.

The controller looks like this:

public function postDestroy() {

        $user = User::find(Auth::user()->id);
        $user = DB::delete('delete from users')->user(id);
        return Redirect::route('site-home')->with('global', 'Your account has been deleted!');

}

I'm trying to grab the current Auth (logged in) user and use their id to delete them from the database. Then send them to the home page with a message.

Also, do I need to make sure the session is properly closed during this process, such as Auth::logout(); ?

I'm pretty new to Laravel, so any help would be appreciated.

Answer

user3657823 picture user3657823 · Aug 7, 2014

Not sure how your routing looks like, but this should do the job.

    $user = \User::find(Auth::user()->id);

    Auth::logout();

    if ($user->delete()) {

         return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
    }

You should logout user before delete.