Laravel Get the Nearest Location by Distance (in Miles)

Hello Artisans, today I'll show you how to find the nearest location where distance is given in miles. Today we'll use a simple query to fetch the nearest user based on our current location. Let's see how we can easily implement in our Laravel Application.

Note: Tested on Laravel 9.19.

Get Nearest Users

Here we'll use a simple mysql raw query to get the distance of users from our given latitude and longitude. We'll use mysql in built function ST_Distance_Sphere() which gives me the distance in miles. Look at the below code snippet.

public function getLocations(Request $request)
        $lat = $request->lat;
        $lon = $request->lon;
        $dis = $request->distance;

        return User::selectRaw("latitude,longitude,id,name,name,location,ST_Distance_Sphere(
                Point($lon, $lat),
                Point(longitude, latitude)
            ) * ? as distance", [.000621371192])->when($dis,function ($query) use($lat,$lon,$dis){
                Point($lon, $lat),
                Point(longitude, latitude)
             ) * .000621371192 <  ? ", $dis); //here distance is calculated by mile.

So, here what we do actually is, at first we'll calculate the distance in miles by requested longitude and latitude and after that we'll check that if distance is request or not. If distance is requested then we'll filter the user only beyond that location.

That's it for today which is a small tip for you. Hope you've enjoyed this tutorial as well as it can be helpful for you. Thanks for reading. ๐Ÿ™‚