Luke Curtis

Luke Curtis

Software Developer and Project Manager

Contact Me

Simple Geosearch in Laravel

01/04/2019 (2 months ago) | Luke Curtis

There are plenty of packages out there that take the hassle of finding results in and around a latitude and longitude. Grimzy's laravel-mysql-spatial feels like the most complete package. However usually I'll find myself needing something ultra simple.

You don't really need a package to do this sort of query and it can actually be contained to a simple scope.

Say for example you have a latitude and longitude on a model, and you're sending a latitude and a longitude to a scope with a radius you want to search within. The query is actually quite simple.

Our simple scope

Our simple scope

So with this scope we can call something like Post::aroundLatLng(27.4698, 153.0251, 50) which would return all posts that were published within 50KMs of Brisbane. Super neat.

Also here's the gist. It's a bit of confusing maths but with PHP it's actually relatively readable.