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

rob_utopano's avatar

Return JSON-Response if call was from API otherwise show view

Hey guys,

My application have a API and Web-Frontend. If the user calls the logout-method from API my method should return a JSON response, if the logout-request comes from Web-Frontend it should behave like the standard and redirect to the start page.

At this moment my LoginController implements the following function to logout the user from API:

    public function logout(Request $request)
    {
        $user = Auth::guard('api')->user();
            if ($user) {
                $user->api_token = null;
                $user->save();
            }
        return response()->json(['data' => 'User logged out.'], 200);
    }

How can i achieve my goal explained above.

Thanks for everyone who can help!

Best regards!

0 likes
1 reply
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

According to the title

if (request()->wantsJson()) {
    return $json;
}

return view('view');
1 like

Please or to participate in this conversation.