Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel response with keyBy returns object instead and array

I'm developing a project setting a back-end RESTful API with Laravel and Front-end with angularJS. I was returning from my controller@index the simple all()->toArray() like this:

A.

return Response::json([
    'val' => myModel::all()->toArray()
]);

Then with that object in angular I could do things like $scope.myArray=response.val and eventually actions like $scope.myArrayBoundToATable.push(newelement). The resulting JSON would be better if it is key'ed by its id so I changed it to:

B.

return Response::json([
    'res' => myModel::all()->keyBy('id')->toArray()
]);

But now all functions like .splice and .push throws an error. By logging to console I could see: With all()->toArray(): [Object] everything works fine. with keyBy('id')->toArray() : Object {1: Object}

I have to rewrite CRUD operations on the $scope.myVar as a JS Object, and not as an array.

I could use method A. and iterate every element to search for an ID, but method B. allows me to access elements in a more elegant way: $scope.myVar(ID).

like image 594
Anfelipe Avatar asked Feb 13 '15 18:02

Anfelipe


1 Answers

This is an associative array as @lukasgieter pointed out. For ease of consumption in the frontend just convert the associative array to a regular array using array_values

Here is how I handle it.

Response::json(['val' => array_values(myModel::all())]);
like image 67
Adedoyin Akande Avatar answered Oct 20 '22 01:10

Adedoyin Akande