PHPackages                             clickbar/laravel-magellan - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. clickbar/laravel-magellan

ActiveLibrary[Database &amp; ORM](/categories/database)

clickbar/laravel-magellan
=========================

This package provides functionality for working with the postgis extension in Laravel.

2.1.0(2mo ago)423715.4k—5.9%26[2 PRs](https://github.com/clickbar/laravel-magellan/pulls)1MITPHPPHP ^8.2CI passing

Since Jan 4Pushed 2mo ago8 watchersCompare

[ Source](https://github.com/clickbar/laravel-magellan)[ Packagist](https://packagist.org/packages/clickbar/laravel-magellan)[ Docs](https://github.com/clickbar/laravel-magellan)[ RSS](/packages/clickbar-laravel-magellan/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (28)Versions (25)Used By (1)

    ![The logo for laravel-magellan, which shows a small blue paper ship with the package name right beside it.](art/logo_light.png)

A modern PostGIS toolbox for Laravel

[![Latest Version on Packagist](https://camo.githubusercontent.com/5b7c6a16fb113b5644a0a9fd6488e3783b9e89570ef68bf8eea41ab12d768012/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636c69636b6261722f6c61726176656c2d6d6167656c6c616e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/clickbar/laravel-magellan)[![Total Downloads](https://camo.githubusercontent.com/733ec8e2a52c88b26910e6634e7a854ca47cb78b4710bb6c75fcd69abd456743/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636c69636b6261722f6c61726176656c2d6d6167656c6c616e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/clickbar/laravel-magellan)

- [Introduction](#introduction)
- [Requirements](#requirements)
- [Installation](#installation)
- [Upgrading from 1.x to 2.x](#upgrading-from-1x-to-2x)
- [What's included](#whats-included)
- [Before you start](#before-you-start)
- [Creating Tables with PostGIS Columns](#creating-tables-with-postgis-columns)
- [Preparing the Model](#preparing-the-model)
- [Using the geometry data classes](#using-the-geometry-data-classes)
- [Generators &amp; Parsers](#generators--parsers)
- [Request Validation and Transformation](#request-validation-and-transformation)
- [Interaction with the database](#interaction-with-the-database)
    - [Example Setup](#example-setup)
    - [Insert/Update](#insertupdate)
    - [Insert/Update with different SRID](#insertupdate-with-different-srid)
    - [Select](#select)
    - [Using PostGIS functions in queries](#using-postgis-functions-in-queries)
    - [Alias in select](#alias-in-select)
    - [Geometry or Geography](#geometry-or-geography)
    - [Autocast for BBox or geometries](#autocast-for-bbox-or-geometries)
- [Limitations](#limitations)
    - [Database Name Prepending (Cross Database Connections)](#database-name-prepending-cross-database-connections)
- [Testing](#testing)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [Security Vulnerabilities](#security-vulnerabilities)
- [Thanks](#thanks)
- [Credits](#credits)
- [License](#license)

Introduction
------------

[](#introduction)

Every sailor needs a nice ship to travel the seven seas ⛵️

This package will have you prepared for accessing [PostGIS](https://postgis.net) related functionality within Laravel. It was heavily inspired by [mstaack/laravel-postgis](https://github.com/mstaack/laravel-postgis), but has evolved into much more since. Other than some slight changes, you should be familiar with Magellan very quickly.

Magellan comes with paddles included and also provides parsers/generators for GeoJson, WKB &amp; WKT out of the box. Easily use all PostGIS datatypes in your migrations and avoid raw SQL to access PostGIS functions by using our Builder functions.

Additionally `laravel-magellan` provides extensions to the Schema, Query Builder and Postgres Grammar for easy access of PostGIS database functions like `ST_EXTENT`. It does all this without breaking compatibility to other packages, like [tpetry/laravel-postgresql-enhanced](https://github.com/tpetry/laravel-postgresql-enhanced), which has to extend the Grammar and Connection.

Requirements
------------

[](#requirements)

Magellan supports Laravel projects, which meet the following requirements:

- Laravel `^11.0` or `^12.0` or `^13.0`
- PHP `^8.2`

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require clickbar/laravel-magellan
```

You can publish and run the migrations with:

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

You can publish the config file with:

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

You may find the contents of the published config file here: [config/magellan.php](config/magellan.php)

Upgrading from 1.x to 2.x
-------------------------

[](#upgrading-from-1x-to-2x)

Please see [UPGRADING](UPGRADING.md) for details.

What's included
---------------

[](#whats-included)

- Migration Schema Blueprints
- Geometry Data Classes
- WKT Generator &amp; Parser
- WKB Generator &amp; Parser
- GeoJson Generator &amp; Parser
- Eloquent Model Trait
- Command to automatically add the PostGIS trait to models
- GeoJson Request Validation Rule
- Transforms Geometry for Form Requests
- Exposes nearly all PostGIS functions as typed functions that can be used in select, where, orderBy, groupBy, having, from
- Geometry and BBox Cast classes
- Auto Cast when using functions that return geometry or bbox
- Empty Geometry Support
- Automatic PostGIS Function Doc Generator
- Custom Geometry Factories &amp; Models
- More tests
- ...

Before you start
----------------

[](#before-you-start)

We highly recommend using the [laravel-ide-helper](https://github.com/barryvdh/laravel-ide-helper) from barryvdh to be able to see everything included in the IDEs auto-completion.

Creating Tables with PostGIS Columns
------------------------------------

[](#creating-tables-with-postgis-columns)

Note

Please use the new built-in Laravel methods `geometry` and `geography` where possible.
Only the `magellanBox2D`, `magellanBox3D`, `magellanGeometryCollection`-functions are not deprecated.
All other methods are deprecated and will be removed in the next major version.

Laravel-magellan extends the default Schema Blueprint with all PostGIS functions. Since Laravel has introduced basic geometry support, all methods are prefixed with `magellan`. e.g.

```
// Deprecated, use the new Laravel methods instead ->geometry('location', 'POINT', 4326)
$table->magellanPoint('location', 4326);

// Special column types (not deprecated)
$table->magellanBox2D('bounds2d');
$table->magellanBox3D('bounds3d');
$table->magellanGeometryCollection('collection');
$table->magellanGeometryCollectionM('collection_m');
$table->magellanGeometryCollectionZ('collection_z');
$table->magellanGeometryCollectionZM('collection_zm');
```

Preparing the Model
-------------------

[](#preparing-the-model)

In order to properly integrate everything with the model you only need to add the appropriate cast (each Geometry and Box can be used):

```
protected $casts = [
    /** ... */
    'location' => Point::class,
    'bounds' => Box2D::class,
];
```

Using the geometry data classes
-------------------------------

[](#using-the-geometry-data-classes)

We've included data classes for the following common geometries:

- Point
- LineString
- Polygon
- MultiPoint
- MultiLineString
- MultiPolygon
- GeometryCollection

To create a geometry object manually, use the suited `::make` method. e.g.

```
$point = Point::make(51.087, 8.76);
```

You will notice that there are 3 different make methods for the Point class with different parameters:

1. `make(...)`
2. `makeGeodetic(...)`
3. `makeEmpty(...)`

Let's take a closer look to the first two:

This is the default factory method that can be used to fill all possible values. This method is considered the "plain" way. You should consider using this method when you use a non LNG/LAT projection (e.g. something different from WGS84:SRID=4326).

```
function make(float $x, float $y, ?float $z = null, ?float $m = null, ?int $srid = null): self
```

Most of the common web use cases use the WGS84 projection. Therefore, most of the time the terms that are used will be latitude, longitude and altitude instead of x, y and z. To provide more comfort we have included a factory method that accepts those terms and automatically sets the SRID to the default geodetic SRID, which can be set in the config file.

```
function makeGeodetic(float $latitude, float $longitude, ?float $altitude = null, ?float $m = null): self
```

When using a Point class that uses a geodetic projection, you can access the latitude, longitude and altitude with properly named getters and setters:

- `function getLatitude(): float`
- `function setLatitude(float $latitude): void`
- `function getLongitude(): float`
- `function setLongitude(float $longitude): void`
- `function getAltitude(): ?float`
- `function setAltitude(float $altitude): void`

An exception will be thrown if you try to use this functions on a Point without a srid listed in the geodetic\_srids config. Use the default x, y, z, m getters and setters instead.

Generators &amp; Parsers
------------------------

[](#generators--parsers)

We currently provide parsers &amp; generators for the following formats:

- EWKB
- EWKT
- GeoJson

These are also used to format our data classes to strings, convert the return value from the database (which comes in EWKB format) and output our data to the frontend as GeoJson for example.

> **Note**In the following we will use EWKB &amp; WBK or EWKT &amp; WKT interchangeably, even though we always use the extended version of each.

The config file allows you to customize which representation you would like to be used eg. when JSON serialization is done for our data classes, where GeoJson is otherwise the default.

```
$point = Point::makeGeodetic(51.087, 8.76);

json_encode($point); // returns GeoJson
// "{"type":"Point","coordinates":[8.76,51.087]}"
```

You can always use instances of each parser / generator and parse / generate on your own behalf.
While Generators have to be created on demand, Parsers are already instanciated in the app container as singletons and you can use them as follows:

```
$parser = app(WKTParser::class);

$point = $parser->parse('SRID=4326;POINT (2, 2)');

$generator = new WKBGenerator();

$generator->generate($point);
// "0101000020E610000000000000000000400000000000000040"
```

In this example we obtain an instance of the `WKTParser` and convert the string to one of our data classes. `$point` is then a valid `Point` instance, and we can use any other generator e.g. the `WKBGenerator` to output the `$point` in hexadecimal WKB format.

Request Validation and Transformation
-------------------------------------

[](#request-validation-and-transformation)

When a form request contains a geometry in GeoJson format, you can use the `GeometryGeojsonRule` for validation. You can even limit the types of allowed geometries by passing an array with the classes.

In order to properly continue working with the received geometry you can use the `TransformsGeojsonGeometry` trait to use automatic transformation of the GeoJson to the proper geometry object. Therefore, return the keys in the `geometries(): array` function.

> **Note**Currently we only support simple field transformation. Arrays &amp; wildcard notation support will follow.

```
class StorePortRequest extends FormRequest
{
    use TransformsGeojsonGeometry;

    public function rules(): array
    {
        return [
            'name' => ['required', 'string'],
            'country' => ['required', 'string'],
            'location' => ['required', new GeometryGeojsonRule([Point::class])],
        ];
    }

    public function geometries(): array
    {
        return ['location'];
    }
}
```

Interaction with the database
-----------------------------

[](#interaction-with-the-database)

### Example Setup

[](#example-setup)

For demo purpose we consider the following fictional scenario:

> We are a sails person with a lovely boat and a database of several ports all over the world.
> For each port we store the name, the country and the location.

Here is the migration we use to create the ports table:

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

and the model implementation:

```
class Port extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'location' => Point::class,
    ];
}
```

### Insert/Update

[](#insertupdate)

Magellan geometry objects can be inserted directly as long as they are specified in the `$casts` of the affected model. In our case, we can insert a new Port like this:

```
Port::create([
    'name' => 'Magellan Home Port',
    'country' => 'Germany',
    'location' => Point::makeGeodetic(49.87108851299202, 8.625026485851762),
]);
```

When you want to update a geometry you can either assign the new location to the model and call `save()` or use the `update()` method on the query builder:

```
$port->location = Point::makeGeodetic(55, 11);
$port->save();

// -- or --

Port::where('name', 'Magellan Home Port')
    ->update(['location' => Point::makeGeodetic(55, 11)]);
```

### Insert/Update with different SRID

[](#insertupdate-with-different-srid)

When getting Geometries from external systems you might receive them in another projection than the one in the database. Consider we want to insert or update a geometry with a different SRID. To do so, we have to use the `ST::transform(...)`function first.

```
$point = Point::make(473054.9891044726, 5524365.310057224, srid: 25832);

Port::create([
    'name' => 'Magellan Home Port',
    'country' => 'Germany',
    'location' => ST::transform($point, 4326),
]);

// -- or --

$port = Port::find(1);

$port->query()->update([
    'location' => ST::transform(Point::make(473054.9891044726, 5524365.310057224, srid: 25832), 4326),
]);
```

### Select

[](#select)

When selecting data from a model that uses the `GeometryCast`, the attributes will directly be parsed to the internal Geometry data classes:

```
$port = Port::first();
dd($port->location);
```

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

There might be cases where you also want to use Box2D or Box3D as column types. Currently, we don't support boxes within the `GeometryCast`. Please use the `BBoxCast` instead.

### Using PostGIS functions in queries

[](#using-postgis-functions-in-queries)

A big part of laravel-magellan is its extensive query building feature. To provide a seamless and easy use of PostGIS functions, we have included a wide scope of the typically ST-prefixed functions that can directly be used with Laravel's query builder.

Whenever you want to use a PostGIS function on a query builder, you can use the default built-in select, where, groupBy, ... functions.

> **Note**
> Using the `where` with a `MagellanExpression` that returns a boolean always requires a following true or false.
>
> That's Laravel default behaviour when using the `$query->where()`, but since PHP supports stuff like `if($boolean)` without the explicit `$boolean == true` condition, the true/false will easily be forgotten, resulting in a null check query instead a boolean query.

```
->where(ST::contains('location', 'polygon'), true)
```

So you can just use the `ST::` functions. Each of these functions returns a `MagellanExpression`.
A *MagellanExpression* is a wrapper around a `ST`-prefixed function from PostGIS. When sailing with Magellan, you should never have to write `ST_xxx` in raw SQL for yourself. Therefore, we have included some paddles.

Most of the `ST`-prefixed functions can be accessed using the static functions on the `ST` class. But enough talk, let's start sailing (with some examples):

**Note:** The necessary classes can be imported as follows:

```
use Clickbar\Magellan\Data\Geometries\Point;
use Clickbar\Magellan\Database\PostgisFunctions\ST;
```

Assuming we have our ships current position and want to query all ports with their distance:

```
$currentShipPosition = Point::makeGeodetic(50.107471773560114, 8.679861151457937);
$portsWithDistance = Port::select() // use select() because we want SELECT *, distance and not only the distance
    ->addSelect(ST::distanceSphere($currentShipPosition, 'location')->as('distance_to_ship'))
    ->get();
```

Since we cannot sail over the whole world, let's limit the distance to max. 50.000 meters:

```
$currentShipPosition = Point::makeGeodetic(50.107471773560114, 8.679861151457937);
$portsWithDistance = Port::select()
    ->addSelect(ST::distanceSphere($currentShipPosition, 'location')->as('distance_to_ship'))
    ->where(ST::distanceSphere($currentShipPosition, 'location'), '
