【问题标题】:Laravel - controller can tell whether request is from web or api route?Laravel - 控制器可以判断请求是来自 web 还是 api 路由?
【发布时间】:2019-05-23 05:36:01
【问题描述】:

所以基本上我希望路由 web 和 api 中的以下内容实际上转到同一个控制器,但基于它是来自 web 还是 api,那么它将返回 html 或 json。

那么在这个控制器内部有没有办法知道请求来自哪个路由?

【问题讨论】:

  • 给出的答案非常可靠 - 但是,如果你想检查 json 而不是 api 路由,你可以检查 $request->ajax() - 我通常为它设置 ajax 中间件like this answer

标签: laravel


【解决方案1】:

您可以使用检查以 api 开头的路径包含:

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

(以上假设你所有的api路由都以api/为前缀)

Request Path

starts_with()

或者您可以使用wantsJson() 方法来检查请求是否希望返回JSON。

if (request()->wantsJson())

就我个人而言,我认为执行这两项检查没有任何问题。这样,api 路由将始终返回 json,但如果非 api 路由出于某种原因需要 json,它也可以得到它:

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

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2013-12-11
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2010-10-15
    • 2012-04-07
    • 2014-11-12
    • 2013-01-15
    相关资源
    最近更新 更多