您可以像这样使用Request :: wantsJson():
if (Request::wantsJson()) {
// return JSON-formatted response
} else {
// return HTML response
}
基本上,Request :: wantsJson()所做的是检查请求中的accept头是否为application / json,并根据它返回true或false.这意味着您需要确保您的客户端也发送“accept:application / json”标头.
请注意,我的答案不是确定“请求是来自REST API”,而是检测客户端是否请求JSON响应.我的答案应该仍然是这样做的方法,因为使用REST API并不需要JSON响应. REST API可能会返回XML,HTML等.
/**
* Determine if the current request is asking for JSON in return.
*
* @return bool
*/
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}