TechnicalEloquent performance

Eloquent performanceLesson 28 of 28

Filter by Geospatial Area

"Which things are in this area?" ST_Contains.

1 min readIntermediateLesson

Eloquent performance28

The problem

Customers are points on a map. Sales regions are shapes. Which customers are in a region, and which region is a customer in?

The fix

Store regions in a geometry column and use ST_Contains(area, point).

✕ Instead of this

Customer::all()->filter(
    fn ($c) => pointInPolygon($c->location, $region->geometry)
);
// every customer and the region shape loaded into PHP

✓ Do this

public function scopeInRegion($query, Region $region)
{
    $query->whereRaw('ST_Contains(?, customers.location)', [$region->geometry]);
}

The benefit

Only customers inside the region are returned, and the shape check runs in the database.

More detail

The region a customer is in:

public function scopeHasCustomer($query, Customer $customer)
{
    $query->whereRaw('ST_Contains(regions.geometry, ?)', [$customer->location]);
}

Why it works

ST_Contains answers "is this point inside this shape?" in the database, so you never load shapes or customers into PHP to check.

Watch out

  • Region shapes can come from public shape files, or be drawn in QGIS (a free mapping app) and exported.

Frame from lesson 28

Filtering by area: only customers (white dots) inside the pink Prairies region are returned, using ST_Contains(region geometry, customers.location).

Key takeaway

"Which things are in this area?" ST_Contains.

Check yourself

What does ST_Contains(region, point) return for a customer outside the region?

Reveal answer

✓ Answer

False (0), so the customer is filtered out.