Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change response in Laravel?

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.

like image 614
Darama Avatar asked Nov 26 '25 12:11

Darama


2 Answers

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;
}
like image 88
Rwd Avatar answered Nov 28 '25 02:11

Rwd


You can use for this Response macros. For example in AppServiceProvider inside boot method you can add:

\Response::macro('custom', function($view, $data) {
    if (\Request::input('format') == 'json') {
            return response()->json($data);
    }
    return view($view, $data);
});

and in your controller you can use now:

$data = [
   'key' => 'value',
];

return response()->custom('your.view', $data);

If you run now for example GET /categories you will get normal HTML page, but if you run GET /categories?format=json you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.

like image 37
Marcin Nabiałek Avatar answered Nov 28 '25 03:11

Marcin Nabiałek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!