【问题标题】:Laravel how to make all controller returned data as jsonLaravel如何使所有控制器返回的数据为json
【发布时间】:2017-11-15 21:57:40
【问题描述】:

如何通过不重复我的代码使我的控制器返回的数据是 json。

样品控制器

public function getTeams(Request $request){
    $result = Team::where('competitionId',$request->input('competitionId',9224))
        ->orderBy('teamName')    
        ->get(['teamId as id','teamName as name']);
    return response($result, 200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Content-Type', 'application/json');
}

public function getTeamStats(Request $request) {
    if($request->id){
        $result = TeamCompetitionStatistics::getTeamStats($request->id);
        return response($result, 200)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Content-Type', 'application/json');
    }
}

如你所见,我已将这部分重复了两次

return response($result, 200)
->header('Access-Control-Allow-Origin', '*')
->header('Content-Type', 'application/json');

他们是不是以更好的方式做到这一点?

【问题讨论】:

    标签: php json laravel laravel-5 backend


    【解决方案1】:

    创建一个 Trait,您将把它包含在需要重用某些逻辑的每个控制器中。您可以像这样在特征内的函数中抽象这些行:

    trait MyResponseTrait{
    
        public function successfulResponse($result)
        {
          return response($result, 200)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Content-Type', 'application/json');
        }
    }
    

    您的代码将如下所示:

    public function getTeams(Request $request){
        $result = Team::where('competitionId',$request->input('competitionId',9224))
            ->orderBy('teamName')    
            ->get(['teamId as id','teamName as name']);
        return successfulResponse($result);
    }
    
    public function getTeamStats(Request $request) {
        if($request->id){
            $result = TeamCompetitionStatistics::getTeamStats($request->id);
            return successfulResponse($result)
    
        }
    }
    

    请注意,您必须在 Controller 中包含 Trait,例如:

    class Controller extends BaseController
    {
        use MyResponseTrait;
        // Will be able to call successfulResponse() inside here...
    }
    

    更多关于traits...

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      Laravel 包含一个 JSON 响应,但如果您只返回集合,Laravel 5.4 也会输出 JSON。

      JSON 响应文档:

      https://laravel.com/docs/5.4/responses#json-responses

      JSON 响应

      json 方法会自动将 Content-Type 标头设置为 application/json,并使用 json_encode PHP 函数将给定数组转换为 JSON:

      return response()->json([
          'name' => 'Abigail',
          'state' => 'CA'
      ]);
      

      如果你想创建一个 JSONP 响应,你可以结合使用 json 方法和 withCallback 方法:

      return response()
              ->json(['name' => 'Abigail', 'state' => 'CA'])
              ->withCallback($request->input('callback'));
      

      除此之外,执行重复逻辑的一种简单方法是将其提取到基本控制器类中的方法中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-20
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-07
        • 1970-01-01
        • 2020-07-29
        相关资源
        最近更新 更多