Skip to content

Instantly share code, notes, and snippets.

@goosechaser
Last active May 15, 2018 16:40
Show Gist options
  • Save goosechaser/07dbf28818cedc1c9bb5 to your computer and use it in GitHub Desktop.
Save goosechaser/07dbf28818cedc1c9bb5 to your computer and use it in GitHub Desktop.
Eloquent with raw query in Lararavel: geolocation by latitude, longitude and radius.
// MODEL
public function scopeDistance($query, $lat, $lng, $radius, $unit = "km")
{
$unit = ($unit === "km") ? 6378.10 : 3963.17;
$lat = (float) $lat;
$lng = (float) $lng;
$radius = (double) $radius;
return $query->select(DB::raw("*
FROM (
SELECT *,
($unit * ACOS(COS(RADIANS($lat))
* COS(RADIANS(lat))
* COS(RADIANS($lng) - RADIANS(lng))
+ SIN(RADIANS($lat))
* SIN(RADIANS(lat)))) AS distance")
)
->whereRaw("lat
BETWEEN $lat - ($radius / 69)
AND $lat + ($radius / 69)
AND lng
BETWEEN $lng - ($radius / (69 * COS(RADIANS($lat))))
AND $lng + ($radius / (69 * COS(RADIANS($lat))))
) d WHERE distance <= $radius");
}
// CONTROLLER
$items = Model::distance($lat, $lng, $radius, "km")
->orderBy("distance")
->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment