Use PostGIS functions in Laravel queries via the ST class
mainMagellan provides a static ST class that returns MagellanExpression objects. These can be used seamlessly within Laravel's query builder methods like select(), addSelect(), where(), orderBy(), and groupBy().
Key Usage Patterns
- Aliasing: Use the
as(string)method on an expression to name the resulting column. - Boolean Expressions: When using
where()with an expression that returns a boolean, you must explicitly provide the boolean value (e.g.,trueorfalse) to avoid null-check queries. - Aggregates/Collections: Use
ST::collect()to pass a collection of geometries to functions likeST::convexHull(). - Casting: Use
AsGeometryorAsGeographyto explicitly cast parameters within a function call.
use Clickbar//... imports
// Select with distance and filter
Port::select()
->addSelect(ST::distanceSphere($currentPos, 'location')->as('distance_to_ship'))
->where(ST::distanceSphere($currentPos, 'location'), '<=', 50000)
->orderBy(ST::distanceSphere($currentPos, 'location'))
->get();
// Complex grouping and hull calculation
Port::query()
->select([
'country',
ST::convexHull(ST::collect('location'))->as('hull'),
ST::area(ST::convexHull(ST::collect('location')))->as('area')
])
->groupBy('country')
->get();
// Explicit casting to Geography for meter-based calculations
Port::query()
->select(ST::buffer(new AsGeography('location'), 50)->as('buffered_location'))
->get();