SteveEdson
SteveEdson

Reputation: 2495

Laravel: Transform JSON response data

Currently, I am returning data like so (basic example):

public function index()
{
    return User::all();
}

However, I want to wrap my responses with some extra meta data, so that they look something like:

{
    'success': true,
    'data': {
       ... // Normal response
     }
}

The success value would be something as simple as statusCode == 200.

I've read about using response macros, response factories, after middlewares, the Fractal library etc

Ideally it will work with all responses, e.g. returning Eloquent Models and Collections, as well as with Response::json($data).

What is the best / right way, at the time of Laravel 5.2, to achieve this?

Thanks.

Upvotes: 1

Views: 2696

Answers (2)

Bharat Geleda
Bharat Geleda

Reputation: 2780

If you're developing a API for Laravel, I'd recommend checking out Dingo. It is one of the most useful package for developing APIs. Dingo uses Fractal to transform the responses. In your application to add such metadata, you could use Transformers in Dingo. There are also a lot of events that you can listen to and modify your data. In your particular example, ResponseWasMorphed would be one of the event that you would listen to.

If you want to continue with your project without adding external package, you can override the response() method in your BaseController which could check and add the needed.

public function response($data, $status)
{
    //calculate parameter based on $status
    $success = ...
    return response(array_merge($data, ['success' => $success]));
}

Upvotes: 2

Christian Gerdes
Christian Gerdes

Reputation: 298

You can use the fractal package for that. Then you can run the response through a transformer and get the proper response. Here's the package for that. https://packagist.org/packages/league/fractal

Upvotes: 0

Related Questions