PHPackages                             jackardios/laravel-eloquent-spatial - 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. jackardios/laravel-eloquent-spatial

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

jackardios/laravel-eloquent-spatial
===================================

Spatial library for Laravel

v4.0.0(4mo ago)07021MITPHPPHP ^8.1CI passing

Since Oct 9Pushed 4mo agoCompare

[ Source](https://github.com/Jackardios/laravel-eloquent-spatial)[ Packagist](https://packagist.org/packages/jackardios/laravel-eloquent-spatial)[ Docs](https://github.com/jackardios/laravel-eloquent-spatial)[ RSS](/packages/jackardios-laravel-eloquent-spatial/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (8)Versions (12)Used By (1)

Laravel Eloquent Spatial
========================

[](#laravel-eloquent-spatial)

[![Latest Version on Packagist](https://camo.githubusercontent.com/2c3f1a45b8c050810af32a91308d4aa2d32d09c9e9f41351d43b8726570a630a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a61636b617264696f732f6c61726176656c2d656c6f7175656e742d7370617469616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jackardios/laravel-eloquent-spatial)[![Total Downloads](https://camo.githubusercontent.com/30c3f2e046a7cb7ef6e0137126170423bcf8063f9824f93b607463b6c7a37004/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a61636b617264696f732f6c61726176656c2d656c6f7175656e742d7370617469616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jackardios/laravel-eloquent-spatial)

Laravel package for working with spatial data types and functions in Eloquent.

Supported Databases
-------------------

[](#supported-databases)

- MySQL 5.7 / 8.x
- MariaDB 10.x
- PostgreSQL 12+ with PostGIS 3.4+

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

[](#requirements)

- PHP 8.1+
- Laravel 10.x / 11.x / 12.x

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

[](#installation)

```
composer require jackardios/laravel-eloquent-spatial
```

Quick Start
-----------

[](#quick-start)

### 1. Create a Migration

[](#1-create-a-migration)

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('places', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->geometry('location', subtype: 'point')->nullable();
            $table->geometry('area', subtype: 'polygon')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('places');
    }
};
```

### 2. Set Up Your Model

[](#2-set-up-your-model)

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Jackardios\EloquentSpatial\Objects\Point;
use Jackardios\EloquentSpatial\Objects\Polygon;
use Jackardios\EloquentSpatial\Traits\HasSpatial;

/**
 * @property Point $location
 * @property Polygon $area
 */
class Place extends Model
{
    use HasSpatial;

    protected $fillable = [
        'name',
        'location',
        'area',
    ];

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

### 3. Work with Spatial Data

[](#3-work-with-spatial-data)

```
use App\Models\Place;
use Jackardios\EloquentSpatial\Objects\Point;
use Jackardios\EloquentSpatial\Objects\Polygon;
use Jackardios\EloquentSpatial\Objects\LineString;
use Jackardios\EloquentSpatial\Enums\Srid;

// Create a place with a point location
// Note: Point constructor uses (longitude, latitude) order
$place = Place::create([
    'name' => 'Eiffel Tower',
    'location' => new Point(2.2945, 48.8584),
]);

// Create with SRID
$place = Place::create([
    'name' => 'Big Ben',
    'location' => new Point(-0.1246, 51.5007, Srid::WGS84),
]);

// Create with polygon area
$place = Place::create([
    'name' => 'Central Park',
    'area' => new Polygon([
        new LineString([
            new Point(-73.9819, 40.7681),
            new Point(-73.9580, 40.8006),
            new Point(-73.9498, 40.7969),
            new Point(-73.9737, 40.7644),
            new Point(-73.9819, 40.7681), // Close the ring
        ]),
    ]),
]);

// Access coordinates
echo $place->location->longitude; // 2.2945
echo $place->location->latitude;  // 48.8584
echo $place->location->srid;      // 4326 (if using WGS84)

// Convert to different formats
$place->location->toWkt();     // POINT(2.2945 48.8584)
$place->location->toJson();    // {"type":"Point","coordinates":[2.2945,48.8584]}
$place->location->toArray();   // ['type' => 'Point', 'coordinates' => [2.2945, 48.8584]]
```

Geometry Classes
----------------

[](#geometry-classes)

All geometry classes support creating instances from various formats:

```
use Jackardios\EloquentSpatial\Objects\Point;

// From constructor
$point = new Point(longitude: 2.2945, latitude: 48.8584, srid: 4326);

// From WKT
$point = Point::fromWkt('POINT(2.2945 48.8584)', srid: 4326);

// From GeoJSON
$point = Point::fromJson('{"type":"Point","coordinates":[2.2945,48.8584]}');

// From array
$point = Point::fromArray(['type' => 'Point', 'coordinates' => [2.2945, 48.8584]]);

// From WKB
$point = Point::fromWkb($binaryData);
```

### Available Geometry Types

[](#available-geometry-types)

ClassDescription`Point`Single coordinate (longitude, latitude)`LineString`Ordered sequence of Points`Polygon`Closed shape defined by LineStrings`MultiPoint`Collection of Points`MultiLineString`Collection of LineStrings`MultiPolygon`Collection of Polygons`GeometryCollection`Mixed collection of any geometry types`BoundingBox`Rectangular bounds with antimeridian support### Coordinate Validation

[](#coordinate-validation)

The `Point` class validates coordinates automatically:

```
// Valid coordinates
$point = new Point(180, 90);    // OK
$point = new Point(-180, -90);  // OK

// Invalid coordinates throw InvalidArgumentException
$point = new Point(200, 0);     // Error: Longitude must be between -180 and 180
$point = new Point(0, 100);     // Error: Latitude must be between -90 and 90
```

Spatial Query Scopes
--------------------

[](#spatial-query-scopes)

The `HasSpatial` trait provides query scopes for spatial operations:

### Distance Queries

[](#distance-queries)

```
use App\Models\Place;
use Jackardios\EloquentSpatial\Objects\Point;

$referencePoint = new Point(-0.1246, 51.5007, 4326);

// Add distance to results
$places = Place::query()
    ->withDistanceSphere('location', $referencePoint)
    ->get();

foreach ($places as $place) {
    echo $place->distance; // Distance in meters
}

// Filter by distance
$nearbyPlaces = Place::query()
    ->whereDistanceSphere('location', $referencePoint, '
