How to find nearest location using latitude and longitude in laravel
In this post, i would like to fine neareby place using latitude and longitude query in laravel eloquent. you can simply get nearest geolocation by mysql radius query in laravel 5, laravel 6, laravel 7 and laravel 8.
If you have places, hotels, home, city, state, country, products, dealer, supplier etc with latitude and longitude location then you can simply find easily nearby you. so let's see following sq query that can simply use in laravel model query.
Here is you can see sql query:
6371 * acos(cos(radians(" . $lat . "))
* cos(radians(posts.lat))
* cos(radians(posts.lon) - radians(" . $lon . "))
+ sin(radians(" .$lat. "))
* sin(radians(posts.lat))) AS distance
Example:
$lat = YOUR_CURRENT_LATTITUDE;
$lon = YOUR_CURRENT_LONGITUDE;
DB::table("posts")
->select("posts.id"
,DB::raw("6371 * acos(cos(radians(" . $lat . "))
* cos(radians(posts.lat))
* cos(radians(posts.lon) - radians(" . $lon . "))
+ sin(radians(" .$lat. "))
* sin(radians(posts.lat))) AS distance"))
->groupBy("posts.id")
->get();
I hope it can help you...

My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
- How to get location information from ip address in Laravel ?
- How to Clear Log File using Command in Laravel?
- Laravel Localization(trans helper) tutorial example
- Ajax - Cross-Origin Request Blocked in Larave?
- How to add charts in Laravel using Highcharts ?
- How to use DB transactions in Laravel?
- How to get months difference between two dates in Laravel?
- How to set URL without http of Other site in Laravel?
- How to get Lat and Lon from google map API in Jquery PHP?