2

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.

japose7523
  • 29
  • 2
  • 15
  • I have the exact same logout function and it works, are you sure your routes are protected by web middleware ? Perhaps you are logged out but still have access to routes you should not have access to when not logged in – Lk77 Aug 22 '22 at 12:09
  • Another possible issue is that your login controller is protected by the guest middleware, which prevent logged in users to call your logout action, in that case you should add the logout route to the exceptions of the guest middleware with `$this->middleware('guest')->except('logout');` in the constructor – Lk77 Aug 22 '22 at 12:17

1 Answers1

2

Use the below code in your custom logout function

Auth::logout();

Studocwho
  • 2,404
  • 3
  • 23
  • 29
Asad
  • 27
  • 3
  • 1
    He already call the logout function : `$this->guard()->logout();` is the same has `Auth::logout();` – Lk77 Aug 22 '22 at 12:12
  • 1
    `Auth::logout()` is the shorthand for the logout via `Auth::guard()->logout()`. – Dan Aug 22 '22 at 12:15