crawlingdeveloper's avatar

Logout not working

I am new to Laravel

I am busy creating an API and I have the registration working and the login working. I am using Postman to test.

I cannot get the logout to work and I keep getting an error in the postman console telling me: Route [login] not defined.

So I presume Laravel is routing you to the web based login route after logging out, but since this is an api there is no web based login route. Why is Laravel redirecting you to the login route if you are using Sanctum and the project is using api.php? Does Laravel not know it's an API? How do I get past this so the user token gets deleted and I just get a json response?

Here is my logout controller file:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LogoutController extends Controller
{
    public function logout(Request $request)
    {
        $user = Auth::guard('sanctum')->user();

        if ($user) {
            $user->currentAccessToken()->delete();
            return response()->json(['message' => 'Logout successful'], 200);
        }

        return response()->json(['message' => 'No user logged in'], 401);
    }
}

and here is my route: Route::middleware('auth:sanctum')->post('/logout', [LogoutController::class, 'logout']);

0 likes
7 replies
experimentor's avatar
Level 25

Add header

 "Accept": "application/json"

This tells laravel that you are expecting an xhr response instead of the default redirect to login page.

crawlingdeveloper's avatar

Ok thanks but then what is the header content-type with the same value for?

experimentor's avatar

@crawlingdeveloper The Content-Type indicates to the server the format of the request data. The Accept header again specifies the desired response format.

crawlingdeveloper's avatar

I set the best answer and presume that sets it to resolved. Don't see a button to mark it as resolved

1 like

Please or to participate in this conversation.