I am POST-ing an array of objects to my API. How can I access the properties of those objects?

Viewed 48

I have the following database table:

Table: Locations
Columns: id, lat, lng, user_id

I'm currently POST-ing a markers array the contains 2 JavaScript objects from the front-end to the back-end that have lat and lng properties. I'm trying to figure out how would I assign the lat and lng properties in my foreach loop. I just can't figure out how to access them.

My POST

    data: function() {
        return {
            markers: [{lat: 42, lng: 24}, {lat: 11, lng: 22}]
        }
    },
    methods: {
        saveLocations(){
            axios.post('/location', {
                userId: 1,
                markers: this.markers
            }).then(response => {
                console.log(response);
            }).catch((error) => console.log(error));
        }
    }

PHP

public function newLocation(Request $request){
    $markers = $request['markers'];

    foreach ($markers as $marker) {
        $location = new Location();
        $location->user_id = 1;
        $location->lat = ;
        $location->lng = ;
        $location->save();
    }

    return response()->json([
        'message' => 'Successfully added locations!'
    ], 201);
}
1 Answers

inside your foreach loop use it like this

foreach ($markers as $marker) {
        $location = new Location();
        $location->user_id = 1;
        $location->lat = $marker['lat'];
        $location->lng = $marker['lng'];
        $location->save();
}
Related