Reputation: 5782
My goal is to make an GET axios/ajax call to the database which has records with latitude and longitude and then combine the 2 latitude and longitude for each record into a single JSON object that have the format of {lat: 20, lng: 20}
. Currently I have this:
public function getLocations(Request $request){
$locations = Location::where('user_id', 1)->get()->toJson();
return response()->json([
'locations' => $locations,
'message' => 'Successfully added locations!'
], 201);
}
I need to somehow pass an array of json objects. I believe it should look like this:
$locations = [ {lat: 10, lng: 10},
{lat: 11, lng: 11},
{lat: 12, lng: 12}
]
With one JSON object for every record in $locations. The lat and lng are located in $locations. For example $locations->lat and $locations->lng. How would I go about creating such an object that I could use on my frontend?
[{"id":40,"user_id":1,"lat":42,"lng":24,"created_at":"2019-01-16 10:14:40","updated_at":"2019-01-16 10:14:40"},
{"id":41,"user_id":1,"lat":43,"lng":25,"created_at":"2019-01-16 10:14:41","updated_at":"2019-01-16 10:14:41"}]
Upvotes: 0
Views: 39
Reputation: 2164
you could do it like this:
public function getLocations(Request $request){
$locations = Location::where('user_id', 1)->get();
$locationsData= [];
foreach ($locations as $location) {
$locationsData[] = ['lat' => $location->lat, 'lng' => $location->lng];
}
return response()->json([
'locations' => $locationsData,
'message' => 'Successfully added locations!'
], 201);
}
Upvotes: 1
Reputation: 8739
Try this, only one line of code:
$locations = Location::where('user_id', 1)->get(['lat', 'lng'])->toJson();
Upvotes: 0