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)
.
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())]);
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