0

I have two applications: SPA built with Vuejs 3 and the API built with Laravel. the SPA is running on 127.0.0.1:5173 and the api is running on 127.0.0.1:8000 The user can authenticate successfully but I Want logging out it's not working, the user stays authenticated without any error thrown

logout function :

public function logout(Request $request)
    {
        if(method_exists(auth()->user()->currentAccessToken(), 'delete')) {
            $request->user()->currentAccessToken()->delete();
        }
        Auth::guard('web')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return response()->json([
            'success' => true,
        ]);
    }

axios request :

 logout() {
          return new Promise((resolve, reject) => {
            axios
              .post('/api/v1/auth/logout')
              .then((response) => {
                resolve(response)
              })

logout route :

//api.php
Route::prefix('/v1')->group(function () {
    Route::group(['prefix' => 'auth'], function () {
        Route::post('logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
    }); 
.....

1 Answer 1

2

if you are using sanctum for your APIs you could do something like this for logging out the user

use Illuminate\Support\Facades\Auth;


    function logoutout(Request $request)
    {
        $request->user()->tokens()->delete(); //to delete the token
        Auth::logout(); //to logout your web
        return response()->json([
            'success' => true,
        ]);
    }
Sign up to request clarification or add additional context in comments.

7 Comments

I have this error Method Illuminate\Auth\RequestGuard::logout does not existe
and I tried Auth::guard('web')->logout(); the error does not thrown but the user is not logged out
I have edited my answer please check and let me know if there is any problem
same error :( @mohammad
just for testing could you please change the name of your method from logout to something else for example like logoutsss(Request $request) and also change your API also and let me know what dose it says
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.