laravellaravel-5

Auth::logout() prioritizing above all code


I'm working on a project which needs an online status on the user so I just added an on auth.logout event to listen for logouts and put the status to false for offline. In the event when logged the $event->user value is null. So I tried checking the function that calls Auth::logout() in my project and for some reason the code is being triggered before all the other code. Does anyone have any idea?

Here it still has the User Model data.

protected function logout()
{
    $user = Auth::user();
    $user->online = 0;
    $user->save()
    //Auth::logout();

    return redirect()->intended(route('page.login'));
}

But here the $user = null

protected function logout()
{
    $user = Auth::user(); //$user = null
    $user->online = 0;
    $user->save();
    Auth::logout(); //Is this taking priority over all code somehow ?

    return redirect()->intended(route('page.login'));
}

Solution

  • There is absolutely no way that code is jumping precedence. If that was possible, software development would be an impossible feat of coincidence and magic -- more so than it already is.

    It's much more likely that that code is executing twice. Try setting up the controller logic so that it can function if $user is null. I would bet money that logout() is running multiple times.

    protected function logout()
    {
        $user = Auth::user();
    
        if ($user)
        {
            $user->online = 0;
            $user->save();
            Auth::logout();
        }
    
        return redirect()->intended(route('page.login'));
    }