dongxingchang9345 2016-05-23 02:17
浏览 112
已采纳

Laravel:基于路由前缀的响应格式

I have some routes in my Laravel application (many routes)

I want to add new functionality, to return all data in JSON format. Now data are just views .

/route1/options /route2/options

etc

i want to have

/json/route1/options /json/route2/options

so, if any my existent route gets a prefix /json then data should be returned with JSON .

My routes looks like normal routes in Laravel

Route::get('user/{id}', function($id) {

    $user = ....
    return view('userprofile', $user);
});

How to change this to know that json format is requested? should it be separate routing group where each route is described again?

  • 写回答

2条回答 默认 最新

  • doulongti5932 2016-05-23 02:32
    关注

    In my eyes the best way to achieve this would be to allow the client to choose what they want. This is typically achieved using the Accept header.

    GET myapp.com/user/1 HTTP/1.1
    Accept application/json
    

    This method is good when writing applications in Laravel as the request object is always informed if JSON is requested via the Accept header.

    I've used Laravel 5.2's implicit model binding in the following examples.

    Route::get('user/{user}', function(Request $request, User $user) {
    
        if ($request->wantsJson()) {
            return response()->json($user);
        }
    
        return view('userProfile', $user);
    });
    

    This method avoids putting unnecessary information in the url keeping your API clean. However a route that many go down (myself included) is to separate routes that return data and routes that return views.

    Route::get('user/{user}', function(Request $request, User $user) {
        // Standard route, return a view
    });
    
    Route::get('api/user/{user}', function(Request $request, User $user) {
        // API route, always return JSON
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部