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?
If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }
JSON data has the concept of null and empty arrays and objects.
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.
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() .
This works in Laravel 5.6
Route::get('/test2', function (){
$data = (object) [];
return response()->json($data, 200, [], JSON_FORCE_OBJECT);
});
This works:
return response()->json(new stdClass());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With