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

devk's avatar
Level 3

How to tell if a request is made to the API routes

Hi, so I'm trying to implement the render method of an Exception, but since I use the exception in both api routes and stateful routes, I need to be able to tell if it's api or not.

I could just check the first segment of the URL, but seems hacky. Maybe there's a way to check if the request went through api middleware? Or anything even more straightforward?

Thanks

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You can use the wantsJson method on the Request object to determine what the client needs:

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

return view(...);

It is not exactly guaranteed that the route was in the api group or web but it respects what the client has set in the Accepts header.

1 like
devk's avatar
Level 3

Yeah that seems good. For my use case, I think I'll actually settle for ! $request->hasSession() + (||) your suggestion.

Thanks!

Please or to participate in this conversation.