php - Laravel: Transform JSON response data

946

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 asstatusCode == 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 withResponse::json($data).

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

Thanks.

713

Answer

Solution:

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 theresponse() method in yourBaseController 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]));
}
313

Answer

Solution:

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

People are also looking for solutions to the problem: php - Get response code using smtp.com with phpmailer

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.