Laravel 8 custom logout method not working and not logs out the user

Viewed 89

I'm working with Laravel 8 and I wanted to build my own logout method like this:

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

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

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

        if ($response = $this->loggedOut($request)) {
            return $response;
        }

        return $request->wantsJson()
            ? new JsonResponse([], 204)
            : redirect('/');
    }

And I have created this link just like the Laravel's default auth system:

<div class="profile-user-loggedin">
    <a href="{{ route('logout') }}">
        <img src="img/icon-logout.png" style="width: 26px;" alt="" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
    </a>
    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
        {{ csrf_field() }}
    </form>
</div>

And here is the route:

Route::post('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');

Now when I click on the link to logout the user, it properly redirects to the homepage of website but the problem is that the user is still logged in somehow!

I don't know really what's going wrong here since I the route and method looks fine.

So if you know, please help me out with this...

Thanks.

1 Answers

Use the below code in your custom logout function

Auth::logout();

Related