所以基本上我想要在路由 web 和 api 中的以下内容实际上转到同一个控制器,但基于它是来自 web 还是 api 然后它将返回 html 或 json。
那么在这个控制器内部有没有办法知道请求来自哪个路由?
您可以使用检查以 api 开头的路径包含:
if (starts_with(request()->path(), 'api'))
Run Code Online (Sandbox Code Playgroud)
(以上假设您所有的 api 路由都以 为前缀api/)
或者您可以使用该wantsJson()方法来检查请求是否希望返回 JSON。
if (request()->wantsJson())
Run Code Online (Sandbox Code Playgroud)
就个人而言,我认为执行这两项检查都没有任何问题。这样 api 路由将始终返回 json 但如果由于某种原因非 api 路由需要 json 它也可以得到它:
if (request()->wantsJson() || starts_with(request()->path(), 'api'))
Run Code Online (Sandbox Code Playgroud)