0

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"}]
3
  • 1
    what does $locations look like? Commented Jan 16, 2019 at 10:23
  • I added the response to my post Commented Jan 16, 2019 at 10:28
  • You can use Laravel APi resource it's a proper way to do it :) Commented Jan 16, 2019 at 10:34

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this, only one line of code:

$locations = Location::where('user_id', 1)->get(['lat', 'lng'])->toJson();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.