How to change response in Laravel?

Darama picture Darama · Feb 19, 2017 · Viewed 7.7k times · Source

I have RESTful service that is available by endpoints.

For example, I request api/main and get JSON data from server.

For response I use:

return response()->json(["categories" => $categories]);

How to control format of response passing parameter in URL?

As sample I need this: api/main?format=json|html that it will work for each response in controllers.

Answer

Rwd picture Rwd · Feb 19, 2017

One option would be to use Middleware for this. The below example assumes that you'll always be returning view('...', [/* some data */]) i.e. a view with data.

When the "format" should be json, the below will return the data array passed to the view instead of the compiled view itself. You would then just apply this middleware to the routes that can have json and html returned.

public function handle($request, Closure $next)
{
    $response = $next($request);

    if ($request->input('format') === 'json') {
        $response->setContent(
            $response->getOriginalContent()->getData()
        );
    }

    return $response;
}