TechnicalEloquent performance

Eloquent performanceLesson 26 of 28

Filter by Geographic Distance

Precompute geometry once instead of on every query.

1 min readIntermediateLesson

Eloquent performance26

The problem

Show only stores within 10 km. Building a point from longitude and latitude for every row costs time (~170 ms).

The fix

Store a precomputed spatial point column and compare against that.

✕ Instead of this

$query->whereRaw(
    'ST_Distance(ST_SRID(Point(longitude, latitude), 4326), ST_SRID(Point(?, ?), 4326)) <= ?',
    [...$coordinates, $distance]
);
// builds a point for every row, every query

✓ Do this

$query->whereRaw(
    'ST_Distance(location, ST_SRID(Point(?, ?), 4326)) <= ?',
    [...$coordinates, $distance]
);

The benefit

About 100 ms faster, because the point is stored once rather than rebuilt on every query.

Results

Query time

~170 ms~70 ms

59% lower

about 100 ms faster

More detail

The migration replaces the two number columns with one point column:

$table->point('location', 4326);

Watch out

  • Seeding with DB::raw("ST_SRID(Point($lng, $lat), 4326)") is fine for a trusted file. Never put user input in raw SQL. Use bindings.

Frame from lesson 26

The seeder writes a precomputed point: 'location' => DB::raw('ST_SRID(Point(lng, lat), 4326)'). Inlining values like this is fine for a trusted CSV, but never for user input.

Key takeaway

Precompute geometry once instead of on every query.

Check yourself

Why did switching to a point column speed things up?

Reveal answer

✓ Answer

The point no longer has to be built from two numbers for every row on every query.