I have a model Location, and it has a one to one relationship with another model Address with attributes like latitude and longitude, and I'm working on an endpoint to get a list of locations based their distance to user. So my GET request, for example, looks something like /locations?latitude=70.00&longitude=-80.01.
In my LocationController I already have a function like haversineGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) that takes 4 arguments as float and return the distance to user input location as a float.
function haversineGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, isMile = false) {
if ($isMile) {
$earthRadius = self::EARTH_RADIUS_IN_MILE;
else {
$earthRadius = self::EARTH_RADIUS_IN_KM;
}
$dLat = deg2rad($latitudeTo - $latitudeFrom);
$dLon = deg2rad($longitudeTo - $longitudeFrom);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earthRadius * $c;
return $d;
}
My question is, how do I use this function as part of my eloquent query to get the distance? My eloquent query currently looks something like this:
$distance = self::haversineGreatCircleDistance($latitude, $longitude, 'latitude', 'longitude') . ' AS distance';
$query = Location::select('*', \DB::raw($distance))
->with('address')
->sortBy('distance');
However it's not working and all the distances calculated are the same as if the second latitude and longitude parameters were 0. And if there's no way to make the query work with php functions, what is a better solution? Please let me know if you need more information. Thanks so much!
DB::raw(), and is the methodhaversineGreatCircleDistancein your Location Model?