Laravel Sorting user collection based by distance

Randy

New Member
#1
Mã:
public function nearby()
{
    $user = auth()->user();

    $lat = auth()->user()->latitude;
    $lon = auth()->user()->longitude;
    $radius = 3; // km => converted to meter

    $angle_radius = (float)$radius / ( 111 * cos( (float)$lat ) ); // Every lat|lon degree° is ~ 111Km
    $min_lat = (float)$lat - (float)$angle_radius;
    $max_lat = (float)$lat + (float)$angle_radius;
    $min_lon = (float)$lon - (float)$angle_radius;
    $max_lon = (float)$lon + (float)$angle_radius;

    $persons = User::where('status', STATUS::ACTIVE)
                ->where('id', '!=', $user->id)
                ->whereBetween('latitude', [$min_lat, $max_lat])
                ->whereBetween('longitude', [$min_lon, $max_lon])
                ->get();

    $persons->each(function($person) {
        /* auth user coordinate vs user's coordinates */
        $point1 = array('lat' => auth()->user()->latitude, 'long' => auth()->user()->longitude);
        $point2 = array('lat' => $person->latitude, 'long' => $person->longitude);
        $distance = $person->getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);

        $person['distance'] = $distance;
    });

    return $persons;

}
I'm searching users within the 3km radius based on user's long/lat. I'm comparing auth long/lat to nearby user long/lat. It returns collections of user with distance.

LjdYj.png

Now I am having trouble sorting it by distance.
If I add orderBy('distance', 'desc') of course it will result an error, because I do not have distance column on my DB.
Is their a way to sort it and paginate it.
 
Top