TechnicalEloquent performance

Eloquent performanceLesson 25 of 28

Get the Distance Between Geographic Points

Distances belong in SQL: ST_Distance returns metres.

1 min readIntermediateLesson

Eloquent performance25

The problem

Show how far each of ~4,500 stores is from the user.

The fix

Let MySQL calculate it with ST_Distance on two GPS points.

✕ Instead of this

Store::all()->map(function ($store) use ($lat, $lng) {
    $store->distance = haversine($lat, $lng, $store->latitude, $store->longitude);
    return $store;
});
// loads all ~4,500 stores into PHP

✓ Do this

In scopeSelectDistanceTo($query, array $coordinates):

if (is_null($query->getQuery()->columns)) {
    $query->select('*');
}

$query->selectRaw('ST_Distance(
    ST_SRID(Point(longitude, latitude), 4326),
    ST_SRID(Point(?, ?), 4326)
) as distance', $coordinates);

The benefit

The database calculates every distance, so you can paginate, filter and sort on it.

Why it works

ST_SRID(Point(lng, lat), 4326) builds a proper GPS point (4326 is the standard GPS coordinate system). The distance comes back in metres.

Watch out

  • Add select('*') first if nothing is selected yet, otherwise you only get the distance column.
  • Point takes longitude first, then latitude.
  • Display in km with number_format($store->distance / 1000, 2).

Frame from lesson 25

scopeSelectDistanceTo: it adds select('*') if no columns are selected yet, then selectRaw('ST_Distance(ST_SRID(Point(longitude, latitude), 4326), ST_SRID(Point(?, ?), 4326))'). The result is in metres.

Key takeaway

Distances belong in SQL: ST_Distance returns metres.

Check yourself

ST_Distance returns 2400. What unit is that?

Reveal answer

✓ Answer

Metres, so 2.4 km.