PHPackages                             shabushabu/laravel-postgis - 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. shabushabu/laravel-postgis

ActiveLibrary

shabushabu/laravel-postgis
==========================

PostGIS query expression collection for Laravel

v0.6.3(1y ago)14157↓100%[3 issues](https://github.com/ShabuShabu/laravel-postgis/issues)MITPHPPHP ^8.2

Since Jun 29Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/ShabuShabu/laravel-postgis)[ Packagist](https://packagist.org/packages/shabushabu/laravel-postgis)[ Docs](https://github.com/shabushabu/laravel-postgis)[ GitHub Sponsors](https://github.com/boris-glumpler)[ RSS](/packages/shabushabu-laravel-postgis/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelogDependencies (16)Versions (13)Used By (0)

[![PostGIS for Laravel](laravel-postgis.png)](laravel-postgis.png)

Laravel PostGIS
===============

[](#laravel-postgis)

[![Latest Version on Packagist](https://camo.githubusercontent.com/0627290520f738efa6880e849a5bba58e1f13c3e14b314fbab86291778f1af18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736861627573686162752f6c61726176656c2d706f73746769732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shabushabu/laravel-postgis)[![Total Downloads](https://camo.githubusercontent.com/350bc29145dd8c4f34fc387d5b8f1464503acbe73ada832d052bab7d36cb598c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736861627573686162752f6c61726176656c2d706f73746769732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/shabushabu/laravel-postgis)

Select collection of Laravel query expressions for PostGIS.

Supported minimum versions
--------------------------

[](#supported-minimum-versions)

PHPLaravelPostgreSQLPostGIS8.211.23163.4Installation
------------

[](#installation)

Caution

Please note that this is a new package and, even though it is well tested, it should be considered pre-release software

Before installing the package you should install and enable the [PostGIS](https://postgis.net/documentation/getting_started/) extension.

You can install the package via composer:

```
composer require shabushabu/laravel-postgis
```

Usage
-----

[](#usage)

Please see the [expressions folder](src/Expressions) for a full list of supported PostGIS functions.

We do accept pull requests for any additional functions!

The expressions can be used in queries or in migrations.

PostGIS queries often have subtle differences between them, so the way we use this package at ShabuShabu is to extend the Eloquent builder for a given model and use the expressions in there.

### Query examples

[](#query-examples)

#### Getting the GeoJSON representation of a geometry column

[](#getting-the-geojson-representation-of-a-geometry-column)

```
use ShabuShabu\PostGIS\Expressions\As;
use Tpetry\QueryExpressions\Language\Alias;
use ShabuShabu\PostGIS\Expressions\Enums\Option;

Track::query()
    ->select(new Alias(new As\GeoJSON('geom', 6, Option::bbox), 'json'))
    ->where('trail_id', 27)
    ->value('json');
```

#### Get a GeoJson Feature collection

[](#get-a-geojson-feature-collection)

```
use ShabuShabu\PostGIS\Expressions\As;
use Tpetry\QueryExpressions\Language\Alias;
use ShabuShabu\PostGIS\Expressions\Casts\AsJson;
use ShabuShabu\PostGIS\Expressions\Helpers\JsonAgg;
use ShabuShabu\PostGIS\Expressions\Helpers\JsonBuildObject;

DB::query()
    ->select([
        new Alias(new JsonBuildObject([
            'type'     => 'FeatureCollection',
            'features' => new JsonAgg(new AsJson(new As\GeoJson('t.*', null, null)))
        ]), 'features')
    ])
    ->from(
        Track::query()->select(['geom', 'id', 'title']), 't'
    );
```

#### Get an elevation profile from a linestring zm

[](#get-an-elevation-profile-from-a-linestring-zm)

```
use Tpetry\QueryExpressions\Language\Alias;
use ShabuShabu\PostGIS\Expressions\Collect;
use ShabuShabu\PostGIS\Expressions\Simplify;
use ShabuShabu\PostGIS\Expressions\DumpPoints;
use ShabuShabu\PostGIS\Expressions\Position\Elevation;
use ShabuShabu\PostGIS\Expressions\Position\Timestamp;

DB::query()->select([
    new Alias(new Elevation('geom'), 'x'),
    new Alias(new Timestamp('geom'), 'y'),
])->from(
    Track::query()->select(
        new Alias(new DumpPoints(new Simplify(new Collect('geom'), 0.15)), 'geom')
    )->where('trail_id', 27), 't'
);
```

#### Get a bounding box for a collection of geometries

[](#get-a-bounding-box-for-a-collection-of-geometries)

```
use Tpetry\QueryExpressions\Language\Alias;
use ShabuShabu\PostGIS\Expressions\Collect;
use ShabuShabu\PostGIS\Expressions\Envelope;
use ShabuShabu\PostGIS\Expressions\Box\TwoD;
use ShabuShabu\PostGIS\Expressions\Math\Round;
use ShabuShabu\PostGIS\Expressions\Casts\AsJson;
use ShabuShabu\PostGIS\Expressions\Casts\AsNumeric;
use ShabuShabu\PostGIS\Expressions\Helpers\MakeArray;
use ShabuShabu\PostGIS\Expressions\Helpers\ArrayToJson;
use ShabuShabu\PostGIS\Expressions\Position\MinLatitude;
use ShabuShabu\PostGIS\Expressions\Position\MaxLatitude;
use ShabuShabu\PostGIS\Expressions\Position\MinLongitude;
use ShabuShabu\PostGIS\Expressions\Position\MaxLongitude;

DB::query()
    ->select([
        new Alias(new AsJson(new ArrayToJson(new MakeArray([
            new Round(new AsNumeric(new MinLongitude('bbox')), 9),
            new Round(new AsNumeric(new MinLatitude('bbox')), 9),
            new Round(new AsNumeric(new MaxLongitude('bbox')), 9),
            new Round(new AsNumeric(new MaxLatitude('bbox')), 9),
        ]))), 'bbox')
    ])
    ->from(
        Track::query()->select([
            new Alias(new TwoD(new Envelope(new Collect('geom'))), 'bbox')
        ]), 't'
    );
```

### Migration examples

[](#migration-examples)

#### Adding a generated column from coordinate columns

[](#adding-a-generated-column-from-coordinate-columns)

```
use ShabuShabu\PostGIS\Expressions\SetSRID;
use ShabuShabu\PostGIS\Expressions\Position\MakePoint;

Schema::create('locations', static function (Blueprint $table) {
    // all the other table columns...

    $table->decimal('lat', 10, 6)->nullable();
    $table->decimal('lng', 10, 6)->nullable();
    $table
        ->geometry('geom', 'point', 4326)
        ->storedAs(new SetSRID(new MakePoint('lng', 'lat'), 4326));
});
```

#### Setting the center for a given multipolygon

[](#setting-the-center-for-a-given-multipolygon)

```
use ShabuShabu\PostGIS\Expressions\Centroid;

Schema::create('countries', static function (Blueprint $table) {
    // all the other table columns...

    $table->geometry('geom', 'multipolygon', 4326);
    $table
        ->geometry('center', 'point', 4326)
        ->storedAs(new Centroid('geom'));
});
```

#### Setting the area in square kilometers

[](#setting-the-area-in-square-kilometers)

```
use ShabuShabu\PostGIS\Expressions\Area;
use Tpetry\QueryExpressions\Value\Value;
use ShabuShabu\PostGIS\Expressions\Math\Round;
use ShabuShabu\PostGIS\Expressions\Casts\AsNumeric;
use ShabuShabu\PostGIS\Expressions\Casts\AsGeography;
use Tpetry\QueryExpressions\Operator\Arithmetic\Divide;

Schema::create('provinces', static function (Blueprint $table) {
    // all the other table columns...

    $table->geometry('geom', 'multipolygon', 4326);
    $table
        ->integer('area_km2')
        ->storedAs(new Round(
            new AsNumeric(
                new Divide(
                    new Area(new AsGeography('geom')),
                    new Value(1e+6)
                )
            )
        ));
});
```

### Model Casts

[](#model-casts)

You can cast your geometry columns to their respective `\Brick\Geo\Geometry` counterparts. Here's an example:

```
use Brick\Geo\Point;
use ShabuShabu\PostGIS\Casts\Geometry;
use Illuminate\Database\Eloquent\Model;

class Location extends Model
{
    // ...

    protected function casts(): array
    {
        return [
            'point' => Geometry::using(Point::class),
        ];
    }
}
```

### Brick/Geo Integration

[](#brickgeo-integration)

All the necessary wiring to use `brick/geo` with PostGIS is already done for you. You can just resolve `ShabuShabu\PostGIS\Geometry` from the container:

```
use Brick\Geo\Polygon;
use ShabuShabu\PostGIS\Geometry;

echo app(Geometry::class)->area(
    Polygon::fromText('POLYGON ((0 0, 0 3, 3 3, 0 0))')
);
```

### Mapbox Vector Tile Server

[](#mapbox-vector-tile-server)

Caution

Please note that atm you will need to install the `develop` branch to use this feature! This feature is not currently covered by any tests, so use at your own risk.

#### Add a gate

[](#add-a-gate)

You will need to add a gate to the `boot` method of your `AppServiceProvider` to ensure that only certain users can use the tile server:

```
Gate::define(
    'access-tile-server',
    static fn (User $user) => $user->is_admin,
);
```

#### Create sources

[](#create-sources)

The next step is to create sources for all your MVTs. All sources should extend the `ShabuShabu\PostGIS\Servers\Tiles\Source` class.

```
