sparkmix
sparkmix

Reputation: 2489

Laravel - controller can tell whether request is from web or api route?

So basically I want the following in routes web and api which actually go to the same controller but base on whether it's from web or api then it will either return html or json.

So inside this controller is there a way to know which routes the request is from?

Upvotes: 3

Views: 3435

Answers (1)

Rwd
Rwd

Reputation: 35190

You could either use check the path starts with api contains:

if (starts_with(request()->path(), 'api')) 

(the above assumes that all of your api routes are prefixed with api/)

Request Path

starts_with()

or you could use the wantsJson() method to check if the request wants JSON to be returned.

if (request()->wantsJson())

Personally, I wouldn't see any issue with performing both checks. This way the api route will always return json but if for whatever reason the non-api route needed the json it could get it as well:

if (request()->wantsJson() || starts_with(request()->path(), 'api'))

Upvotes: 7

Related Questions