Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shashi_verma's avatar

How to Show JSON response when we hit logout method in api?

I have created an api, and there is a method logout in it. first i log in , and get a token., and then i hit the logour api url , then there i have to fill headers with authorization = bearer + token, then i logged out successfully, but if i again hit the logout url, i got an error something like login doesnot exist, i want to show json response at that time how can i achieve that.

0 likes
9 replies
m7vm7v's avatar

In your logout() method you could have an

if( auth()->guest() ) {
    return response()->json([
    'name' => 'Name',
    ]);
}
shashi_verma's avatar

@m7vm7v Thanks for the reply

public function logout(Request $request) {

    if( auth()->guest() )
    {
        return response()->json([
            'name' => 'Name',
        ]);
    }
    else
    {
        $token='Bearer '.$request->bearerToken();
    $request->user()->token()->revoke();
    return response()->json([
        'message' => 'Successfully logged out'
    ]);

    }
}

This is my logout method now, and i am still getting this error, in postman

InvalidArgumentException Route [login] not defined.

Guru5005's avatar
Guru5005
Best Answer
Level 3
public function logout(){
        if (Auth::check()) {
            Auth::user()->token()->revoke();
            return response()->json(['success' =>'Successfully logged out of application'],200);
        }else{
            return response()->json(['error' =>'api.something_went_wrong'], 500);
        }
    }

that is how i do it.

shashi_verma's avatar

@rugiguru thanks bro that works, Please help me with one more thing, in my postman when I change the HTTP type from post to get or get to post I get an error but there is nothing like

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

how can I show json here, Thansk once again

Guru5005's avatar

@SHASHI_VERMA - It depends on your controller method and api route

example: in routes/api.php

 Route::get('/', 'exampleController@example');

and your controller should be like

public function example(){
        $success['message'] = "Testing admin routes";
        return response()->json(['success' => $success], 200);
    }

in post man use get method and url

Guru5005's avatar

Why do u want to hit a end point with a different kind of request?. even i could not get the ans.

Please or to participate in this conversation.