区分来自网络路由的呼叫与API路由的呼叫? [英] Distinguish between a call from web route vs API route?
问题描述
在我的 web.php
文件中,我的路由看起来像这样:
In my web.php
file, I have a route that looks like this:
Route::get('/', 'HomeController@getFeed');
在我的 api.php
文件中,我的路由看起来像这样:
And in my api.php
file, I have a route that looks like this:
Route::get('feeds', 'HomeController@getFeed');
请注意,它们都调用相同的方法 getFeed()
.
Notice that they both call the same method, getFeed()
.
在控制器的方法中,是否可以区分调用是来自Web路由还是来自API路由?我需要能够返回两种不同的响应,一种用于Web路由,一种用于API路由.
Is there a way to distinguish whether the call came from the web route vs the API route in the controller's method? I need to be able to return two different responses, one for the web route and one for the API route.
这是 HomeController.php
类:
class HomeController extends Controller
{
public function getFeed() {
$user = Auth::user();
// How to check if call is from web route or API route?
// Need to return two different responses for each scenario.
}
}
谢谢.
推荐答案
来自api.php的所有路由都会自动以"api/"作为前缀因此,您可以使用以下代码检查他
All routes from api.php are automatically prefixed with 'api/' So you can use he below code to check
if (Request::is('api*')) {
echo "request from api route";
exit();
}else{
echo "request from web";
exit();
}
这篇关于区分来自网络路由的呼叫与API路由的呼叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!