10

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.

apxcode
  • 7,696
  • 7
  • 30
  • 41
Jack Barham
  • 3,197
  • 10
  • 41
  • 62

2 Answers2

18

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.

user3657823
  • 291
  • 2
  • 4
1

You merely gotta do like this:

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

Amit Roy
  • 11
  • 3