I am fetching data from database then adding one more property to that object which is distance. and sorting object data based on that property. When I dd() it in controller to check if data is sorted or not. I see that data is sorted but when I return it as JSON response it returned as it comed from database.
controller function
public function search(Request $request)
{
$providers = Provider::get()->map(function($item) use($request){
$item->setAttribute('distance',$this->addDistanceToProvider($item,$request)) ;
return $item;
})->sortBy('distance');
dd($providers);
return response()->json($providers);
}
My Answer:
>map(function($provider) {
$provider->distance = $this->calculateDistance($provider->latitude, $provider->longitude, $request->latitude, $request->longitude);
return $provider;
});
$providers = $providers->sortBy('distance');
return response()->json($providers);
}
private function calculateDistance($lat1, $lon1, $lat2, $lon2) {
// Calculate distance between two coordinates
}
In the above code, I am first fetching the providers from the database and then adding a distance property to each provider object. I am then sorting the providers based on the distance property. When I dd() the $providers variable, I can see that the data is sorted correctly. However, when I return the $providers as a JSON response, the data is not sorted as expected.
To fix this issue, you can convert the sorted collection to an array before returning it as a JSON response. Here's the updated code:
php
public function search(Request $request)
{
$providers = Provider::get()->map(function($provider) {
$provider->distance = $this->calculateDistance($provider->latitude, $provider->longitude, $request->latitude, $request->longitude);
return $provider;
});
$providers = $providers->sortBy('distance')->values()->all();
return response()->json($providers);
}
By using the `values()->all()` method after sorting the collection, you are converting the sorted collection to a plain array, which will maintain the sorting order when returned as a JSON response.
Rate this post
4 of 5 based on 6954 votesComments