PenAndPapers PenAndPapers -4 years ago 92
JSON Question

Laravel how to make all controller returned data as json

How can I make my controllers that it's returned data is a json by not repeating my code.

Sample Controller

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');
}
}


as you can see I have repeated this section twice

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


Is their a way to do this in much better way?

Answer Source

Create a Trait, which you will include in every controller that needs to reuse certain logic. You could abstract those lines in a function inside the trait like so:

trait MyResponseTrait{

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

And your code will look like this:

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)

    }
}

Note that you will have to include the Trait inside your Controller, for example:

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

More on traits...

I hope this helped!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download