Ad

How Do I Iterate This Array Of Object In Laravel Controller?

- 1 answer

I make a ajax call on click button and then send the array data to the controller. So this is the ajax call:

const saveBtnOnClick = () => {
        //e.preventDefault();
        loopMarker(poly);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: "{{ route('storeRouteMap') }}",
            type: 'POST',
            data: {markers: markers},
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log("Error " + response);
            }
        })
    }

And the data passing in payload developer tools looks like this:

markers[0][lat]: 3.2845171928345853
markers[0][long]: 101.8885194254942
markers[0][sequence]: 0
markers[0][route_id]: 5
markers[1][lat]: 3.591580368128944
markers[1][long]: 102.5367127848692
markers[1][sequence]: 1
markers[1][route_id]: 5

In the controller:

public function store(Request $request): JsonResponse
{
    $out = new ConsoleOutput();
    $routeMaps = $request->all();

    $out->writeln($routeMaps[1]['long']);

    try{
        foreach($routeMaps as $key=>$value){
            $out->writeln($value['lat']);
            $out->writeln($value['long']);
            $out->writeln($value['sequence']);
            $out->writeln($value['route_id']);
        }

But $out->writeln($value['lat']) gives error, Undefined array key 'lat' and $out->writeln($routeMaps[1]['long']) gives error, Undefined array key 1; So how did this array structured for me to iterate?

Ad

Answer

You are passing data in form of key value i.e. markers: markers. So your request parameter in controller would be like: $request->markers. You need to iterate through $request->markers.

$routeMaps = $request->markers;

foreach($routeMaps as $key => $value){
   $out->writeln($value['lat']);
   $out->writeln($value['long']);
   $out->writeln($value['sequence']);
   $out->writeln($value['route_id']);
}

Hopefully this would work :)

Ad
source: stackoverflow.com
Ad