Often, in real-estate , dating  and other similar websites, you might have noticed how they allow you to search nearby to any location. You can easily accomplish that in your laravel application using Haversine formula.

nearby location in laravel

Source -- Tighten.co

Last year, I worked on real-estate project in my college as an capstone project and that's when I got to work on this query. Though haversine formula is easy to find but to use it in laravel through Eloquent was very difficult. I tried many solutions found in Stackoverflow, laracasts forum and other sources but couldn't make them work. Some of them did work but since they were using raw queries, I couldn't paginate the results which is what I needed.

After some trial and error, I finally make it working. So, here I am sharing the code snippet.

      $gr_circle_radius = 6371;
      $max_distance = 500;

      $distance_select = sprintf(
                                    ( %d * acos( cos( radians(%s) ) " .
                                            " * cos( radians( lat ) ) " .
                                            " * cos( radians( long ) - radians(%s) ) " .
                                            " + sin( radians(%s) ) * sin( radians( lat ) ) " .
                                        " ) " . 

        $properties =  Property::select('*')
        ->having(DB::raw($distance_select), '<=', $max_distance)

Here, I have set maximum distance = 500 Km so it will show all results within 500 Km of the given Latitude and Longitude (used $lat, $long as variables).

To see the Demo, Check out my real estate project -- FirstFloor

Posted by Parth Patel

I am a web developer and a tech blogger. I love to share information about latest tech trends as well as programming knowledge. Currently living in Canada, I want to master web development and then pour my knowledge to my fellow readers.

One Comment

  1. sir in my page i have a scroll bar..by scrolling it i got km(eg.22km).and im getting the current latitude and longitude..with these values how i get the schools in a range of 22 km..my maximum km value is 100…i want laravel query for this..plz help


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.