dongxingchang9345 2016-05-23 10: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 10: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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?