The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

Handling Geospatial Data with Laravel Magellan

Last updated on by

Handling Geospatial Data with Laravel Magellan image

Geospatial data is important in many applications, from mapping services to ride-sharing apps and even logistics. Whether you're tracking a fleet of delivery vehicles, building a store locator, or analyzing geographic patterns, the ability to efficiently store, query, and manipulate location data can be a very important skill for developers. With geospatial data you can map objects, events, and other real-world phenomena to a specific geographical area identified by latitude and longitude coordinates.

If you are building applications in this area and using PostgreSQL, you will probably use PostGIS.

PostGIS

PostGIS is an extension for the PostgreSQL relational database that adds support for storing, indexing, and querying geospatial data. PostGIS offers the following features:

  • Spatial Data Storage, for example, points, lines, polygons, and multi-geometries, in both 2D and 3D data.
  • Spatial Indexing
  • Spatial Functions that can allow you to filter and analyze spatial data, measuring distances and areas, intersecting geometries, buffering, and more.
  • Geometry Processing, which allows for the processing and manipulating of geometry data, such as simplification, conversion, and generalization.
  • Storage and processing of raster data, such as elevation data and weather data.
  • Functions for geocoding and reverse geocoding.
  • Integration with third-party tools such as QGIS, GeoServer, MapServer, ArcGIS, and Tableau.

Most cloud providers will already have PostGIS installed and you need to enable it. To enable PostGIS, connect to your database as the postgres user or another super-user account, and run:

CREATE EXTENSION postgis;

Thats it! PostGIS is now enabled.

You can find out what version you have with postgis_full_version().

SELECT PostGIS_Full_Version();

However, if you are running your own system, and want to install PostGIS directly on it yourself, here are some basic instructions.

Laravel and Geospatial Data

Laravel by itself, does not natively support much of the functionality needed to handle and work with geospatial data. But assuming you are using PostgreSQL and have PostGIS already installed it allows you to use the geography and geometry methods in your migrations to add a GEOGRAPHY or GEOMETRY equivalent column with the given spatial type and SRID (Spatial Reference System Identifier). For example:

$table->geography('coordinates', subtype: 'point', srid: 4326);
$table->geometry('positions', subtype: 'point', srid: 0);

This may be all you need in certain cases, but querying geospatial data can be made even easier and you can gain additional functionality with the help of a package like Laravel-Magellan.

Laravel-Magellan

Laravel-Magellan simplifies working with PostGIS by providing built-in tools like parsers and generators for GeoJSON, Well-Known Text (WKT), and Well-Known Binary (WKB). It supports all PostGIS data types in migrations and allows access to PostGIS functions through Builder methods, eliminating the need for raw SQL. It was created by the team at Clickbar and is an improvement on the now archived mstaack/laravel-postgis package (not to be confused with the another Laravel PostGIS package which we will try to cover in a subsequent article).

You can install the package via Composer:

composer require clickbar/laravel-magellan

You can then publish and run the migrations with:

php artisan vendor:publish --tag="magellan-migrations"
php artisan migrate

And finally, you can publish the config file with:

php artisan vendor:publish --tag="magellan-config"

Now instead of using the Laravel default geography and geometry types, Magellan extends the default Schema Blueprint with all PostGIS functions and these methods are prefixed with magellan. e.g.

$table->magellanPoint('location', 4326);
$table->magellanGeometry('location', 4326);
$table->magellanGeography('location', 4326);
$table->magellanBox2D('location', 4326);
$table->magellanBox3D('location', 4326);
$table->magellanLineString('location', 4326);

and many more.

Magellan also provides geometry classes, for common geometries, such as Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.

To create a geometry object you can use the generic <GeometryClass>::make method. For instance, to create a Point, specify its x and y coordinates.

$point = Point::make(26.193056, -80.161111);

The Point class also has the makeGeodetic() factory method, which creates a point from latitude, longitude and altitude coordinates. However, for simplicity our examples will only use latitude and longitude.

$point = Point::makeGeodetic(26.193056, -80.161111);

If you're curious, a geodetic point is a specific location on the Earth's surface defined by its latitude, longitude, and elevation. And a geodetic line is the shortest path between two points on Earth's curved surface.

Scenario

As an example, lets put together a scenario of storing Football (Soccer) stadiums and their locations.

Schema::create('stadiums', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('capacity');
$table->string('country');
$table->magellanPoint('location');
$table->timestamps();
});

Our model could look like this:

class Stadium extends Model
{
use HasFactory;
use HasPostgisColumns;
 
protected $guarded = [];
 
protected array $postgisColumns = [
'location' => [
'type' => 'geometry',
'srid' => 4326,
],
];
}

To add a new Stadium, we could write the following code in a Controller:

Stadium::create([
'name' => 'Old Trafford',
'capacity' => 74310,
'country' => 'United Kingdom',
'location' => Point::makeGeodetic(53.463493, -2.292279),
]);

And to query for the location of a Stadium using Magellan we could write:

$stadium = Stadium::first();
dd($stadium->location);

Which will return something like:

Clickbar\Magellan\Data\Geometries\Point {#1732
#srid: 4326
#dimension: Clickbar\Magellan\Data\Geometries\Dimension {#740
+name: "DIMENSION_2D"
+value: "2D"
}
#x: -2.292279
#y: 53.463493
#z: null
#m: null
}

If we then wanted to access the latitude, longitude and altitude values, we can use the getLatitude(), getLongitude() and getAltitude() methods.

$stadium->location->getLatitude();
$stadium->location->getLongitude();
$stadium->location->getAltitude();

Another big reason to use Laravel Magellan is its extensive query-building features. Whenever you want to use a PostGIS function on a query builder, you will want to use one of the builder methods which are prefixed with st. For example, stSelect, stWhere, stOrWhere, etc.

For example, if we were at a particular location and wanted to know which stadiums are nearby, we could try the following:

use Clickbar\Magellan\Data\Geometries\Point;
use Clickbar\Magellan\Database\PostgisFunctions\ST;
 
$myCurrentPosition = Point::makeGeodetic(53.4634962, -2.2948593);
$stadiumsNearBy = Stadium::select()
->stSelect(ST::distanceSphere($myCurrentPosition, 'location'), 'distance_to_stadium')
->stWhere(ST::distanceSphere($myCurrentPosition, 'location'), '<=', 20000)
->get();

Note: The distances returned by ST::distanceSphere() are in meters.

Laravel Magellan also provides simple validation of geometry in GeoJSON format. For example:

class StoreStadiumRequest extends FormRequest
{
use TransformsGeojsonGeometry;
 
public function rules(): array
{
return [
'name' => ['required', 'string'],
'capacity' => ['required', 'integer'],
'country' => ['required', 'string'],
'location' => ['required', new GeometryGeojsonRule([Point::class])],
];
}
 
public function geometries(): array
{
return ['location'];
}
}

By leveraging PostgreSQL and the PostGIS extension, developers can efficiently store, query, and manipulate location data. Laravel-Magellan further simplifies the process by providing a user-friendly interface to PostGIS functionalities.

Learn more about Laravel Magellan and view the source code on Github.

Yannick Lyn Fatt photo

Staff Writer at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Chief: Run Claude Code on Large Projects with Task-Based Workflows image

Chief: Run Claude Code on Large Projects with Task-Based Workflows

Read article
Laravel OpenAPI CLI: Generate Artisan Commands from Your API Spec image

Laravel OpenAPI CLI: Generate Artisan Commands from Your API Spec

Read article
Improved Skill and Guideline Detection in Laravel Boost v2.2.0 image

Improved Skill and Guideline Detection in Laravel Boost v2.2.0

Read article
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article