jackhammer013
jackhammer013

Reputation: 2297

Laravel - Logout redirects to home instead of logging out

I'm using Laravel 5.1. I have a custom logout function in AuthController.php, what I added on it is just calculating the total login hours of the user and just updating a specific table. My problem is when I click logout it just redirects me to /home, now, this doesn't happen all the time but it happens is fairly easy to reproduce. When I clicked logout it just redirects to /home then I clicked again, same thing. Sometimes I took me 4 attepmts to click the logout button before It logs out and send me to login page. What is happening here? Here's my code:

public function getLogout()
{

    if (Auth::check())
    {
        $userid = Auth::user()->id;

        date_default_timezone_set('Asia/Taipei');

        $today = date('Y-m-d');
        $logHour = new LoginHour();
        $checkLogin = $logHour->checkLoginHoursOut(intval($userid), $today);

        if($checkLogin != null)
        {
            $loginhours = '';
            $timestamp = date('Y-m-d h:i:s');
            $timestamp2 = strtotime($timestamp);

            $userLastLogin = $checkLogin[0]->timestamp;
            $userLastLogin2 = strtotime($userLastLogin);

            // Get difference in hours
            $diffHours = round(($timestamp2 - $userLastLogin2) / 3600, 2);


            LoginHour::where('date', '=', $today)->
                        where('user_id', '=', $userid)->
                        update(['loginhours' => $checkLogin[0]->loginhours + $diffHours, 'status' => 0, 'timestamp' => $timestamp]);
        }

        Auth::logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/auth/login');

    }
    else
    {
        return Redirect::to('/auth/login');
    }
}

Now you might notice I have a Auth::check() and I need that coz for some reason I don't know why I get a non-property object error in $userid = Auth::user()->id; But it's ok now, problem is I am redirected to /home

I have also declared protected $redirectAfterLogout = '/auth/login'; in top of my controller.

Upvotes: 1

Views: 1157

Answers (2)

Ilario Engler
Ilario Engler

Reputation: 2469

Tested in Laravel 5.3 / 5.4

Specify the URL it should redirect. In LoginController.

protected $redirectLogoutTo = '/login';

In LoginController override the logout method from AuthenticatesUsers Trait.

public function logout(Request $request)
{
    $this->guard()->logout();

    $request->session()->flush();

    $request->session()->regenerate();

    return redirect($this->redirectLogoutTo); // only line that changes
}

Inside this method you can do also other stuff as you like.

Upvotes: 2

patilnitin
patilnitin

Reputation: 1171

Problem is with handle RedirectIfAuthenticated middleware. It checks the request and redirects to {domain}/home. Just remove it and handle using your controller.

Upvotes: -1

Related Questions