适用于API和非API的Laravel资源控制器 [英] Laravel resource controllers for both API and non-API use
问题描述
为也执行AJAX调用API的网站创建资源控制器PhotosController
之后,看来该资源控制器既可以在普通网站上使用,也可以作为API使用.
After creating a resource controller PhotosController
for a website that also does AJAX calls to the API, it appears that the resource controller can be used on both the normal website and as the API.
这将显示ID为1的Photo
的HTML页面
This displays a HTML page for Photo
with id = 1
http://domain.com/photos/1
并且Javascript使用以下内容更新Photo
资源并返回JSON响应
and Javascript uses the following which updates the Photo
resource and returns a JSON response
PUT http://domain.com/api/v1/photos/1
问题:我们是否会有2个PhotoControllers
,一个用于处理API使用情况,一个用于非API?
Question: Will we have 2 PhotoControllers
, one to handle API usage and one for non-API?
推荐答案
否.您可以有两个指向相同控制器和动作的单独路由.
No. You can have two separate routes point to the same controller and action.
Route::get('/photos/1', 'PhotoController@index');
Route::get('/api/v1/photos/1', 'PhotoController@index');
然后,在您的控制器方法中,您可以测试请求是否来自Ajax.
Then, in your controller methods, you can test whether the request is from Ajax or not.
if (Request::ajax()) {
// Do some crazy Ajax thing
}
这篇关于适用于API和非API的Laravel资源控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!