🤹
TALL Stack Tips
  • What is TALL Stack
  • Tailwind
    • Tailwind Resources
    • Swinging Bell Notification Icon
    • Styled Unordered Lists
  • Alpine
  • Alpine Resources
  • Tabbed Content Using Alpine JS
  • Checkbox component with SVG tick
  • Dropdown animation
  • Create a Sliding Puzzle Captcha
  • Laravel
    • Tabler Icons Component
    • Password-less Login with Laravel 8+
    • Password-less Login with Magic Link in Laravel 8
    • Laravel Resources
    • Laravel Breeze Login Conditional Redirect
    • Jetstream Login Conditional Redirect
    • Simplify Laravel CRUD Controllers
    • CSRF and expired login forms
    • CSRF and expired logout forms
    • Add your own logo to Laravel Mail
    • Specify a different mail theme for Notifications
    • Show custom page when email verification link expired
    • Using a mutator to save currency
    • Using Spatie Valuestore to hold frequently accessed settings
    • Using the old() helper
    • Alternatives to using Eloquent Accessor
    • UpdateOrCreate may not update timestamp
    • Use of lockForUpdate()
    • Using S3
    • Super Simple User Based Feature Flags
    • Installing a Specific Version of Laravel
    • Versioning your Laravel Project
    • CSS Cache Busting with your Git Commit SHA
    • Adding column to Database Notifications table
    • Find nearby locations using the Haversine formula in Eloquent query
    • Using Queues on Shared Hosting with Laravel
    • Create Guaranteed Unique Invoice Number in Laravel
    • Send Notification to all team members
    • Protect Staging site with Basic Auth
    • Working with Enums
    • PHP DateTime formatting cribsheet
  • Livewire
    • Livewire Resources
    • Naming Livewire Components
    • Dynamic Cascading Dropdown with Livewire
    • Hiding a button after click
    • Working with Javascript Components
    • SweetAlert2 with Livewire
    • Select Multiple or Checkboxes
    • Clearing checkboxes in Livewire
    • Livewire File Uploads Using S3
    • Simple Log File Viewer
  • Related Resources
    • Testing resources
    • When Composer runs out of memory
    • Deployment
    • Security
    • Scheduler & Cron tips
    • LastPass tips
    • Using Git
    • VSCode Tips
    • Markdown
    • Cpanel resources
Powered by GitBook
On this page
  • Haversine
  • Managing coordinates
  • Eloquent or DB Query Builder

Was this helpful?

  1. Laravel

Find nearby locations using the Haversine formula in Eloquent query

Uses the haversine formula to find all DB records with a location within a specified radius

PreviousAdding column to Database Notifications tableNextUsing Queues on Shared Hosting with Laravel

Last updated 2 years ago

Was this helpful?

Haversine

The haversine formula determines the between two points on a sphere given their and . Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles. (Wikipedia)

Managing coordinates

Personally, I have always found it easier to handle and store coordinates as strings. Very rarely is it required to perform any arithmetic operations on the values.

If your requirements are more complex, and you have mysql 8, consider Spatial queries instead.

Eloquent or DB Query Builder

Add the following to an existing query builder instance, and then not forgetting to call get() or paginate()

The query assumes that your table contains columns called latitude and longitude. You may need to adapt these to suit your use case.

// the centre of your search
$latitude = '56.32124';
$longitude = '-1.342934';

// search radius
$distance = 5;  //(miles - see note)

$query->selectRaw('(3959 * acos (
       cos ( radians(?) )
       * cos( radians( latitude ) )
       * cos( radians( longitude ) - radians(?) )
       + sin ( radians(?) )
       * sin( radians( latitude )))) AS distance',[
           $latitude,
           $longitude,
           $latitude
  ]);
            
  $query->havingRaw('distance <= ? OR 0', [$distance]);

The above assumes that you have distance in miles. If distance is in KM then replace 3959 with 6371.

References:

You can discuss pages on this site at

great-circle distance
longitudes
latitudes
https://dev.mysql.com/doc/refman/8.0/en/spatial-types.html
https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula
https://en.wikipedia.org/wiki/Haversine_formula
https://github.com/snapey/talltips/discussions