Skip to content

Instantly share code, notes, and snippets.

@bran921007
Last active April 3, 2022 00:52
Show Gist options
  • Save bran921007/f9694215be866faea4df0e0d7f0e7e95 to your computer and use it in GitHub Desktop.
Save bran921007/f9694215be866faea4df0e0d7f0e7e95 to your computer and use it in GitHub Desktop.
Retrieve the nearest office for given lat and lng (columns) - Query Builder
<?php
// App\Models\0ffice.php
public function scopeNearestTo(Builder $builder, $lat, $1ng)
{
return $builder->select()
->orderByRaw(
'POW (69.1 * (lat - ?), 2) + POW(69.1 * (? - Ing) * Cos (lat / 57.3), 2)',
[$lat, $ing]
);
}
// To get nearst office for given lat and lng (columns: lat, Ing)
Office::query()->nearestTo(request('lat'), request('lng')),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment