How to correctly return a JSON Response in Laravel?
Asked Answered
V

3

6
    return response()->json([
        'message' => 'No new orders!'
    ]);

Unfortunately, this response is not working? Ideally, I'd like to return a JSON response with 'Message' => 'No new orders!' with a status code 204 No Content.

I have these 2 included files in the controller...

use OhMyBrew\BasicShopifyAPI;
use GuzzleHttp\Client;

This utilizes this built-in helper from vendor/laravel/framework/src/Illuminate/foundation/helpers.php

if (! function_exists('response')) {
    /**
     * Return a new response from the application.
     *
     * @param  \Illuminate\View\View|string|array|null  $content
     * @param  int     $status
     * @param  array   $headers
     * @return \Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
     */
    function response($content = '', $status = 200, array $headers = [])
    {
        $factory = app(ResponseFactory::class);

        if (func_num_args() === 0) {
            return $factory;
        }

        return $factory->make($content, $status, $headers);
    }
}
Vigorous answered 24/10, 2019 at 0:47 Comment(6)
It should be working though. return response()->json(['message' => 'No new orders!'], 204); Are you hitting the right endpoint? Have you tried to see if the request shows up in the network tab of the browser's element inspector?Cotter
@Cotter Yep done that too. still not working. It's beyond me why it's not working even commented everything else out still doesn't wanna play...Vigorous
#53178645Vigorous
How are you making this request? If via javascript, is your request sending through the "Accept" header? Something like Accept: "application/json"?Lilley
What do you mean about not working? You need to be more specific to the problem. If you mean your JS code can't get the desired response, so just show us your JS code!Parachronism
Could you try to open your URL in the Postman? It's the best place to test your JSON response.Parachronism
O
12

To return data as json.. just do this:

public function myCoolFunction()
{
    $data = ['message' => 'No new orders!'];
    
    return response()->json($data, 204);
}

From the documentation:

JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

PS: The default response code returned is 200, so, in case you want to return a 200 response code, you could omit the second param.


Notice that, in order to also receive error details in json format, it'll help that your front-end make the request telling your backend that it expects a json response. To do this, add this header when making requests:

accept: application/json
Ozonize answered 24/10, 2019 at 5:3 Comment(0)
A
3

The thing is content won't work when you use code 204. As you wrote status 204 means no content so if you put any content it won't be used.

So if you need to return content from your response, you need to use other status code (for example 200).

However:

 return response()->json([
        'message' => 'No new orders!'
    ]);

should work without any problem because status 200 is used here so if it doesn't work remove vendor directory and run again composer install because maybe you made some changes in vendor directory by accident. Also you should verify log file stored in storage/logs directory to verify the real problem.

Andre answered 24/10, 2019 at 5:28 Comment(1)
Can we use response()->json(....) in controller's constructor? I have tried but it does not work. Any suggestion. Thanks a lot.Drummer
M
2

If for some reason the response helper doesn't work, you may use this:

https://laravel.com/api/5.8/Illuminate/Contracts/Routing/ResponseFactory.html#method_json

Basically:

use Illuminate\Support\Facades\Response;

return Response::json(['data' => 'data'], 200);
Midrash answered 24/10, 2019 at 1:58 Comment(1)
Getting error Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiableDrummer

© 2022 - 2024 — McMap. All rights reserved.