Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Laravel response()->json() to return empty object instead of empty array

Tags:

json

laravel-5

In Laravel 5.5

Route::get('/test2', function (){
    $data = (object) [];

    return response()->json($data);

});

it always returns [] rather than {}.


another code:

Route::get('/test2', function (){
    $data = (object) [];

    return json_encode($data);

});

it correctly returns {}


I want to use response()->json() helper to return empty object instead of empty array, is it possible?

like image 546
kingshark Avatar asked May 01 '18 08:05

kingshark


People also ask

How check response JSON is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

Can JSON value empty?

JSON data has the concept of null and empty arrays and objects.

What is response JSON in laravel?

JSON ResponseThis method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response.

What is JSON encode in laravel?

Laravel JSON is a small package that makes encoding and decoding JSON a breeze with exceptions thrown on error immediately: A simple wrapper around json_encode() and json_decode() for catching any errors without executing json_last_error() .


2 Answers

This works in Laravel 5.6

Route::get('/test2', function (){
    $data = (object) [];

    return response()->json($data, 200, [], JSON_FORCE_OBJECT);

});
like image 50
bloody numen Avatar answered Oct 22 '22 07:10

bloody numen


This works:

return response()->json(new stdClass());
like image 33
Hamid Mohayeji Avatar answered Oct 22 '22 06:10

Hamid Mohayeji