TechnicalEloquent performance

Eloquent performanceLesson 27 of 28

Order by Geographic Distance

Same expression, now in ORDER BY.

1 min readIntermediateLesson

Eloquent performance27

The problem

Show the closest stores first.

The fix

Order by the same ST_Distance expression.

✕ Instead of this

$query->orderByRaw(
    'ST_Distance(location, ST_SRID(Point(?, ?), 4326)) '.request('direction'),
    $coordinates
);
// SQL injection

✓ Do this

$direction = strtolower($direction) === 'asc' ? 'asc' : 'desc';

$query->orderByRaw(
    'ST_Distance(location, ST_SRID(Point(?, ?), 4326)) '.$direction,
    $coordinates
);

The benefit

Closest stores first, with no way to inject SQL through the direction.

Watch out

  • Whitelist the direction, just like lesson 19. It can't be bound.

Frame from lesson 27

scopeWithinDistanceTo and scopeOrderByDistanceTo both use the precomputed location point column, and the sort direction is whitelisted to asc/desc.

Key takeaway

Same expression, now in ORDER BY.

Check yourself

Which part of this query can't use a ? binding?

Reveal answer

✓ Answer

The asc/desc keyword.