I am trying to return Json response as an array of objects. But instead I got response as object of objects. I have condition_question table where I save question_id and condition_id. I want to retrieve all questions which contains particular condition id. And sort them by answers_number. I am new to Laravel, here is my code:
$conditionsIdArray = array($chosenConditionsIds);
$results = Question::whereIn('question_id', function ($query) use ($conditionsIdArray) {
$query->select('question_id')
->from('condition_question')
->whereIn('condition_id', $conditionsIdArray);
})->get()->sortByDesc('answers_number')->take(5);
return response()->json([
'questions' => $results
], 200);
I get response:
{
"questions": {
"0": {
"question_id": 842,
"question_title": "Qui tempora...",
"question_body": "Repellendus non sint...",
"image": "https://lorempixel.com/640/480/?18901",
"question_view_count": 17,
"votes_number": 9,
"answers_number": 9,
"id_user": 9930,
"created_at": "2019-09-07 09:59:05",
"updated_at": "2019-09-08 18:23:41"
},
"28": {
"question_id": 20346,
"question_title": "Quaerat facere...",
"question_body": "Repudiandae culpa ...",
"image": "https://lorempixel.com/640/480/?91963",
"question_view_count": 2,
"votes_number": 2,
"answers_number": 9,
"id_user": 3546,
"created_at": "2019-09-07 10:07:38",
"updated_at": "2019-09-07 10:07:38"
},etc
}
As you can see, I get object with object. I do not want key/value, just simple array of objects type Question. I am struggling two days now, have tried some different stuff like toArray() but do not know how to solve it. Any help would be most welcome.
response()->json($results, 200)return $results