naneri
naneri

Reputation: 3971

How can I logout user after delete with Laravel?

What is the correct way to logout user after I delete his data in Laravel? I would not like to delete him before, in case of delete process goes with errors.

When I am having this code:

    if($this->userManipulator->softDeleteUser(Auth::user())){
        Auth::logout();
        return redirect(url('login'));
    }

it works fine in the app, but does not work correctly during testing.

Upvotes: 2

Views: 2753

Answers (2)

camelCase
camelCase

Reputation: 5598

As I mentioned in the comments, you must log the user out of your application first since once deleted Eloquent won't be able to locate/logout the user.

Below is a solution that addresses your concern about what to do if the delete fails. It might need adjustment depending on how you have things setup, but this concept will work:

// Get the user
$user = Auth::user();

// Log the user out
Auth::logout();

// Delete the user (note that softDeleteUser() should return a boolean for below)
$deleted = $this->userManipulator->softDeleteUser($user);

if ($deleted) {
    // User was deleted successfully, redirect to login
    return redirect(url('login'));
} else {
    // User was NOT deleted successfully, so log them back into your application! Could also use: Auth::loginUsingId($user->id);
    Auth::login($user);

    // Redirect them back with some data letting them know it failed (or handle however you need depending on your setup)
    return back()->with('status', 'Failed to delete your profile');
}

Upvotes: 2

Producdevity
Producdevity

Reputation: 882

This is not possible, Auth won't be able to located them because Eloquent treats them as deleted.

Solution: You should logout user before delete.

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

Auth::logout();

if ($user->delete()) {

     return Redirect::route('home');
}

Upvotes: 0

Related Questions