Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Deleting auth user account while user is logged in

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.

like image 957
Jack Barham Avatar asked Aug 07 '14 19:08

Jack Barham


2 Answers

You merely gotta do like this:

$user=auth()->user();
$user->delete();

like image 85
Amit Roy Avatar answered Oct 14 '22 22:10

Amit Roy


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.

like image 40
user3657823 Avatar answered Oct 15 '22 00:10

user3657823