├── .github └── workflows │ └── main.yml ├── .gitignore ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── config └── config.php ├── phpunit.xml ├── src ├── Casts │ └── LocationCast.php ├── LaravelSpatialServiceProvider.php ├── Traits │ └── HasSpatial.php └── Types │ └── Point.php └── tests ├── HasSpatialTest.php ├── LocationCastTest.php ├── PointTest.php ├── TestCase.php ├── TestModels └── Address.php └── database └── migrations └── 0000_00_00_000000_create_addresses_table.php /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | 11 | services: 12 | mysql: 13 | image: mysql:8.0 14 | env: 15 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 16 | MYSQL_DATABASE: laravel_spatial_test 17 | ports: 18 | - 3306 19 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 20 | 21 | strategy: 22 | fail-fast: true 23 | matrix: 24 | php: [8.2, 8.3, 8.4] 25 | laravel: [11, 12] 26 | stability: [prefer-lowest, prefer-stable] 27 | 28 | name: P${{ matrix.php }} - L${{ matrix.laravel }} 29 | 30 | steps: 31 | - name: Checkout code 32 | uses: actions/checkout@v4 33 | 34 | - name: Setup PHP 35 | uses: shivammathur/setup-php@v2 36 | with: 37 | php-version: ${{ matrix.php }} 38 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, mysql, mysqli, pdo_mysql, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo 39 | ini-values: error_reporting=E_ALL 40 | tools: composer:v2 41 | coverage: none 42 | 43 | - name: Install dependencies 44 | run: composer update --prefer-dist --no-interaction --no-progress 45 | 46 | - name: Start database server 47 | run: sudo /etc/init.d/mysql start 48 | 49 | - name: Execute tests 50 | env: 51 | DB_PORT: ${{ job.services.mysql.ports['3306'] }} 52 | run: vendor/bin/phpunit --testdox --colors=always --exclude-group skipped 53 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | /.idea 3 | /.phpunit.result.cache 4 | /composer.lock 5 | /.phpunit.cache 6 | .DS_Store -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-spatial` will be documented in this file 4 | 5 | ## 3.1.0 - 2025-05-14 6 | - Expression support added to `get()` method in `LocationCast`. 7 | - Replaced `@test` annotations with `#[Test]` attributes across the test suite for modern PHPUnit syntax. 8 | 9 | ## 3.0.0 - 2025-02-20 10 | - Laravel 12 and PHP 8.4 support added. 11 | - Laravel 10 and below versions are not supported anymore. 12 | - PHP 8.1 and below versions are not supported anymore. 13 | 14 | ## 2.0.1 - 2024-11-27 15 | - Fix the incorrect parameter count error while using `ST_SRID` functions with `MariaDB`. 16 | 17 | ## 2.0.0 - 2024-07-25 18 | - Added Laravel 11 and PHP 8.3 support 19 | 20 | ## 1.7.0 - 2023-05-11 21 | - PHP 8.2 support added. 22 | 23 | ## 1.6.1 - 2023-04-04 24 | - Changed `toGeomFromTextString()` to `toGeomFromText()` in Readme. 25 | - Fixed `with_wkt_options` configuration. 26 | 27 | ## 1.6.0 - 2023-03-30 28 | - Added `MariaDB` support to spatial functions. 29 | - Readme updated for adding a location column with default value to an existing table. 30 | - `toGeomFromTextString()` method added to `Point` class for bulk insert/update operations. 31 | 32 | ## 1.4.2 - 2023-02-16 33 | - Laravel 10 support added. 34 | 35 | ## 1.4.1 - 2022-09-05 36 | - Doctrtine unknown type error fixed. 37 | 38 | ## 1.4.0 - 2022-07-24 39 | - Locations that have zero points are excluded while getting the distance to a given location in `withingDistanceTo` scope. 40 | 41 | ## 1.3.0 - 2022-06-24 42 | - `toWkt()` method added to `Point` class for getting the coordinates as well known text. 43 | - `toPair()` method added to `Point` class for getting the coordinates as pair. 44 | - `toArray()` method added to `Point` class for getting the coordinates as array. 45 | 46 | ## 1.2.0 - 2022-02-08 47 | - Laravel 9 support added. 48 | 49 | # 1.1.2 - 2022-03-08 50 | - Bug fixed for casting location columns that is null. 51 | 52 | # 1.1.1 - 2022-01-20 53 | - `axis-order` added to setter of `LocationCast`. 54 | - `axis-order` added to query in `HasSpatial` trait. 55 | 56 | # 1.1.0 - 2022-01-20 57 | - `Point` type added to Doctrine mapped types in the service provider. 58 | - SRID support added to setter of `LocationCast`. 59 | 60 | ## 1.0.0 - 2022-01-18 61 | - initial release 62 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-12 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-extended-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Tarfin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Spatial 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/tarfin-labs/laravel-spatial.svg?style=flat-square)](https://packagist.org/packages/tarfin-labs/laravel-spatial) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/tarfin-labs/laravel-spatial.svg?style=flat-square)](https://packagist.org/packages/tarfin-labs/laravel-spatial) 5 | ![GitHub Actions](https://github.com/tarfin-labs/laravel-spatial/actions/workflows/main.yml/badge.svg) 6 | 7 | This is a Laravel package to work with geospatial data types and functions. 8 | 9 | It supports only MySQL Spatial Data Types and Functions, other RDBMS is on the roadmap. 10 | 11 | ### Laravel Compatibility 12 | 13 | | Version | Supported Laravel Versions | 14 | |---------|----------------------------| 15 | | `3.x` | `^11.0`, `^12.0` | 16 | | `2.x` | `^8.0, ^9.0, ^10.0` | 17 | 18 | **Supported data types:** 19 | - `Point` 20 | 21 | **Available Scopes:** 22 | - `withinDistanceTo($column, $coordinates, $distance)` 23 | - `selectDistanceTo($column, $coordinates)` 24 | - `orderByDistanceTo($column, $coordinates, 'asc')` 25 | 26 | *** 27 | ## Installation 28 | 29 | You can install the package via composer: 30 | 31 | ```bash 32 | composer require tarfin-labs/laravel-spatial 33 | ``` 34 | 35 | ## Usage 36 | Generate a new model with a migration file: 37 | 38 | ```bash 39 | php artisan make:model Address --migration 40 | ``` 41 | 42 | ### 1- Migrations: 43 | 44 | ``` 45 | ### For Laravel 11 and Above Versions 46 | 47 | From Laravel 11 onwards, migrations are created as follows: 48 | 49 | ```php 50 | use Illuminate\Database\Migrations\Migration; 51 | use Illuminate\Database\Schema\Blueprint; 52 | use Illuminate\Support\Facades\Schema; 53 | 54 | return new class extends Migration { 55 | 56 | public function up(): void 57 | { 58 | Schema::create('addresses', function (Blueprint $table) { 59 | $table->geography('location', subtype: 'point'); 60 | }) 61 | } 62 | 63 | } 64 | ``` 65 | In Laravel 11, the methods **point**, **lineString**, **polygon**, **geometryCollection**, **multiPoint**, **multiLineString**, and **multiPolygon** have been removed. Therefore, we are updating to use the **geography** method instead. The `geography` method sets the default SRID value to 4326. 66 | 67 | #### Issue with adding a new location column with index to an existing table: 68 | When adding a new location column with an index in Laravel, it can be troublesome if you have existing data. One common mistake is trying to set a default value for the new column using `->default(new Point(0, 0, 4326))`. However, `POINT` columns cannot have a default value, which can cause issues when trying to add an index to the column, as indexed columns cannot be nullable. 69 | 70 | To solve this problem, it is recommended to perform a two-step migration like following: 71 | 72 | ### For Laravel 11 and Above Versions 73 | 74 | ```php 75 | public function up() 76 | { 77 | // Add the new location column as nullable 78 | Schema::table('table', function (Blueprint $table) { 79 | $table->geography('location', 'point')->nullable(); 80 | }); 81 | 82 | // In the second go, set 0,0 values, make the column not null and finally add the spatial index 83 | Schema::table('table', function (Blueprint $table) { 84 | DB::statement("UPDATE `addresses` SET `location` = ST_GeomFromText('POINT(0 0)', 4326);"); 85 | 86 | DB::statement("ALTER TABLE `table` CHANGE `location` `location` POINT NOT NULL;"); 87 | 88 | $table->spatialIndex('location'); 89 | }); 90 | } 91 | ``` 92 | 93 | *** 94 | 95 | ### 2- Models: 96 | 97 | Fill the `$fillable`, `$casts` arrays in the model: 98 | 99 | ```php 100 | use Illuminate\Database\Eloquent\Model; 101 | use TarfinLabs\LaravelSpatial\Casts\LocationCast; 102 | use TarfinLabs\LaravelSpatial\Traits\HasSpatial; 103 | 104 | class Address extends Model { 105 | 106 | use HasSpatial; 107 | 108 | protected $fillable = [ 109 | 'id', 110 | 'name', 111 | 'address', 112 | 'location', 113 | ]; 114 | 115 | protected array $casts = [ 116 | 'location' => LocationCast::class 117 | ]; 118 | 119 | } 120 | ``` 121 | 122 | ### 3- Spatial Data Types: 123 | 124 | #### ***Point:*** 125 | `Point` represents the coordinates of a location and contains `latitude`, `longitude`, and `srid` properties. 126 | 127 | At this point, it is crucial to understand what SRID is. Each spatial instance has a spatial reference identifier (SRID). The SRID corresponds to a spatial reference system based on the specific ellipsoid used for either flat-earth mapping or round-earth mapping. A spatial column can contain objects with different SRIDs. 128 | 129 | >For details about SRID you can follow the link: 130 | https://en.wikipedia.org/wiki/Spatial_reference_system 131 | 132 | - Default value of `latitude`, `longitude` parameters is `0.0`. 133 | - Default value of `srid` parameter is `0`. 134 | 135 | ```php 136 | use TarfinLabs\LaravelSpatial\Types\Point; 137 | 138 | $location = new Point(lat: 28.123456, lng: 39.123456, srid: 4326); 139 | 140 | $location->getLat(); // 28.123456 141 | $location->getLng(); // 39.123456 142 | $location->getSrid(); // 4326 143 | ``` 144 | 145 | You can override the default SRID via the `laravel-spatial` config file. To do that, you should publish the config file using `vendor:publish` artisan command: 146 | 147 | ```bash 148 | php artisan vendor:publish --provider="TarfinLabs\LaravelSpatial\LaravelSpatialServiceProvider" 149 | ``` 150 | 151 | After that, you can change the value of `default_srid` in `config/laravel-spatial.php` 152 | 153 | ```php 154 | return [ 155 | 'default_srid' => 4326, 156 | ]; 157 | ``` 158 | *** 159 | #### Configuring WKT options 160 | By default, this package uses the `longitude latitude` order for the coordinate values in the WKT format used by spatial functions. This is necessary for some versions of MySQL, which will interpret coordinate pairs as lat-long unless the `axis-order` option is explicitly set to `long-lat`. 161 | 162 | However, MariaDB reads WKT values as `long-lat` by default, and its spatial functions like `ST_GeomFromText` and `ST_DISTANCE` do not accept an `options` parameter like their MySQL counterparts. This means that using the package with MariaDB will result in a `Syntax error or access violation: 1582 Incorrect parameter count in the call to native function 'ST_GeomFromText'` exception. 163 | 164 | To address this issue, we have added a `with_wkt_options` parameter to the config file that can be used to override the default options. This property can be set to `false` to remove the options parameter entirely, which fixes the errors when using MariaDB. 165 | 166 | ```php 167 | return [ 168 | 'with_wkt_options' => true, 169 | ]; 170 | ``` 171 | *** 172 | #### Bulk Operations 173 | In order to insert or update several rows with spatial data in one query using the `upsert()` method in Laravel, the package requires a workaround solution to avoid the error `Object of class TarfinLabs\LaravelSpatial\Types\Point could not be converted to string`. 174 | 175 | The solution is to use the `toGeomFromText()` method to convert the `Point` object to a WKT string, and then use `DB::raw()` to create a raw query string. 176 | 177 | Here's an example of how to use this workaround in your code: 178 | 179 | ```php 180 | use TarfinLabs\LaravelSpatial\Types\Point; 181 | 182 | $points = [ 183 | ['external_id' => 5, 'location' => DB::raw((new Point(lat: 40.73, lng: -73.93))->toGeomFromText())], 184 | ['external_id' => 7, 'location' => DB::raw((new Point(lat: -37.81, lng: 144.96))->toGeomFromText())], 185 | ]; 186 | 187 | Property::upsert($points, ['external_id'], ['location']); 188 | ``` 189 | 190 | 191 | *** 192 | ### 4- Scopes: 193 | 194 | #### ***withinDistanceTo()*** 195 | 196 | You can use the `withinDistanceTo()` scope to filter locations by given distance: 197 | 198 | To filter addresses within the range of 10 km from the given coordinate: 199 | 200 | ```php 201 | use TarfinLabs\LaravelSpatial\Types\Point; 202 | use App\Models\Address; 203 | 204 | Address::query() 205 | ->withinDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331), 10000) 206 | ->get(); 207 | ``` 208 | 209 | #### ***selectDistanceTo()*** 210 | 211 | You can get the distance between two points by using `selectDistanceTo()` scope. The distance will be in meters: 212 | 213 | ```php 214 | use TarfinLabs\LaravelSpatial\Types\Point; 215 | use App\Models\Address; 216 | 217 | Address::query() 218 | ->selectDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331)) 219 | ->get(); 220 | ``` 221 | 222 | #### ***orderByDistanceTo()*** 223 | 224 | You can order your models by distance to given coordinates: 225 | 226 | ```php 227 | use TarfinLabs\LaravelSpatial\Types\Point; 228 | use App\Models\Address; 229 | 230 | // ASC 231 | Address::query() 232 | ->orderByDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331)) 233 | ->get(); 234 | 235 | // DESC 236 | Address::query() 237 | ->orderByDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331), 'desc') 238 | ->get(); 239 | ``` 240 | 241 | #### Get latitude and longitude of the location: 242 | 243 | ```php 244 | use App\Models\Address; 245 | 246 | $address = Address::find(1); 247 | $address->location; // TarfinLabs\LaravelSpatial\Types\Point 248 | 249 | $address->location->getLat(); 250 | $address->location->getLng(); 251 | ``` 252 | 253 | #### Create a new address with location: 254 | 255 | ```php 256 | use App\Models\Address; 257 | 258 | Address::create([ 259 | 'name' => 'Bag End', 260 | 'address' => '1 Bagshot Row, Hobbiton, Shire', 261 | 'location' => new Point(lat: 25.45634, lng: 35.54331), 262 | ]); 263 | ``` 264 | 265 | #### Usage in Resource: 266 | To get an array representation of a location-casted field from a resource, you can return `parent::toArray($request)`. 267 | 268 | If you need to return a custom array from a resource, you can use the `toArray()` method of the `Point` object. 269 | 270 | ```php 271 | class LocationResource extends JsonResource 272 | { 273 | public function toArray($request) 274 | { 275 | return [ 276 | 'location' => $this->location->toArray(), 277 | ]; 278 | } 279 | } 280 | ``` 281 | 282 | Either way, you will get the following output for the location casted field: 283 | 284 | ```json 285 | { 286 | "lat": 25.45634, 287 | "lng": 35.54331, 288 | "srid": 4326 289 | } 290 | ``` 291 | 292 | ### Testing 293 | 294 | ```bash 295 | composer test 296 | ``` 297 | 298 | ### Changelog 299 | 300 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 301 | 302 | ## Contributing 303 | 304 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 305 | 306 | ### Security 307 | 308 | If you discover any security related issues, please email development@tarfin.com instead of using the issue tracker. 309 | 310 | ## Credits 311 | 312 | - [Turan Karatug](https://github.com/tarfin-labs) 313 | - [All Contributors](../../contributors) 314 | 315 | ## License 316 | 317 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 318 | 319 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tarfin-labs/laravel-spatial", 3 | "description": "Laravel package to work with geospatial data types and functions.", 4 | "keywords": [ 5 | "tarfin-labs", 6 | "laravel-spatial" 7 | ], 8 | "homepage": "https://github.com/tarfin-labs/laravel-spatial", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Turan Karatuğ", 14 | "email": "turan.karatug@tarfin.com", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.2|^8.3|^8.4", 20 | "illuminate/support": "^11.0|^12.0" 21 | }, 22 | "require-dev": { 23 | "doctrine/dbal": "^3.3", 24 | "orchestra/testbench": "^9.0|^10.0", 25 | "phpunit/phpunit": "^10.0|^11.0" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "TarfinLabs\\LaravelSpatial\\": "src" 30 | } 31 | }, 32 | "autoload-dev": { 33 | "psr-4": { 34 | "TarfinLabs\\LaravelSpatial\\Tests\\": "tests" 35 | } 36 | }, 37 | "scripts": { 38 | "test": "vendor/bin/phpunit", 39 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 40 | 41 | }, 42 | "config": { 43 | "sort-packages": true 44 | }, 45 | "extra": { 46 | "laravel": { 47 | "providers": [ 48 | "TarfinLabs\\LaravelSpatial\\LaravelSpatialServiceProvider" 49 | ], 50 | "aliases": { 51 | "LaravelSpatial": "TarfinLabs\\LaravelSpatial\\LaravelSpatialFacade" 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | null, 5 | 'with_wkt_options' => true, 6 | ]; 7 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | src/ 6 | 7 | 8 | 9 | 10 | tests 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Casts/LocationCast.php: -------------------------------------------------------------------------------- 1 | getCoordinates($model, $value); 23 | 24 | if (count($coordinates) > 1) { 25 | $location = explode(',', str_replace(['POINT(', ')', ' '], ['', '', ','], $coordinates[0])); 26 | 27 | return new Point(lat: (float) $location[1], lng: (float) $location[0], srid: (int) $coordinates[1]); 28 | } 29 | 30 | $location = explode(',', str_replace(['POINT(', ')', ' '], ['', '', ','], $value)); 31 | 32 | return new Point(lat: (float) $location[1], lng: (float) $location[0]); 33 | } 34 | 35 | public function set($model, string $key, $value, array $attributes): Expression 36 | { 37 | if (!$value instanceof Point) { 38 | throw new InvalidArgumentException( 39 | sprintf('The %s field must be instance of %s', $key, Point::class) 40 | ); 41 | } 42 | 43 | if ($value->getSrid() > 0) { 44 | return DB::raw($value->toGeomFromText()); 45 | } 46 | 47 | return DB::raw(value: "ST_GeomFromText('{$value->toWkt()}')"); 48 | } 49 | 50 | public function serialize($model, string $key, $value, array $attributes): array 51 | { 52 | return $value->toArray(); 53 | } 54 | 55 | private function getCoordinates($model, $value): array 56 | { 57 | if ($value instanceof Expression) { 58 | preg_match( 59 | pattern: "/ST_GeomFromText\(\s*'([^']+)'\s*(?:,\s*(\d+))?\s*(?:,\s*'([^']+)')?\s*\)/", 60 | subject: (string) $value->getValue($model->getConnection()->getQueryGrammar()), 61 | matches: $matches, 62 | ); 63 | 64 | return [ 65 | $matches[1], 66 | (int) ($matches[2] ?? 0), 67 | ]; 68 | } 69 | 70 | return explode(',', $value); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/LaravelSpatialServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 15 | $this->publishes([ 16 | __DIR__.'/../config/config.php' => config_path('laravel-spatial.php'), 17 | ], 'laravel-spatial'); 18 | } 19 | } 20 | 21 | /** 22 | * Register the application services. 23 | */ 24 | public function register() 25 | { 26 | // Automatically apply the package configuration 27 | $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'laravel-spatial'); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Traits/HasSpatial.php: -------------------------------------------------------------------------------- 1 | getQuery()->columns)) { 18 | $query->select("{$this->getTable()}.*"); 19 | } 20 | 21 | match (DB::connection()->getDriverName()) { 22 | 'pgsql', 'mysql' => $this->selectDistanceToMysqlAndPostgres($query, $column, $point), 23 | 'mariadb' => $this->selectDistanceToMariaDb($query, $column, $point), 24 | default => throw new \Exception('Unsupported database driver'), 25 | }; 26 | } 27 | 28 | public function scopeWithinDistanceTo(Builder $query, string $column, Point $point, int $distance): void 29 | { 30 | match (DB::connection()->getDriverName()) { 31 | 'pgsql', 'mysql' => $this->withinDistanceToMysqlAndPostgres($query, $column, $point, $distance), 32 | 'mariadb' => $this->withinDistanceToMariaDb($query, $column, $point, $distance), 33 | default => throw new \Exception('Unsupported database driver'), 34 | }; 35 | } 36 | 37 | public function scopeOrderByDistanceTo(Builder $query, string $column, Point $point, string $direction = 'asc'): void 38 | { 39 | $direction = strtolower($direction) === 'asc' ? 'asc' : 'desc'; 40 | 41 | match (DB::connection()->getDriverName()) { 42 | 'pgsql', 'mysql' => $this->orderByDistanceToMysqlAndPostgres($query, $column, $point, $direction), 43 | 'mariadb' => $this->orderByDistanceToMariaDb($query, $column, $point, $direction), 44 | default => throw new \Exception('Unsupported database driver'), 45 | }; 46 | } 47 | 48 | public function newQuery(): Builder 49 | { 50 | $raw = ''; 51 | 52 | $wktOptions = config('laravel-spatial.with_wkt_options', true) === true 53 | ? ', \'axis-order=long-lat\'' 54 | : ''; 55 | 56 | foreach ($this->getLocationCastedAttributes() as $column) { 57 | $raw .= "CONCAT(ST_AsText({$this->getTable()}.{$column}$wktOptions), ',', ST_SRID({$this->getTable()}.{$column})) as {$column}, "; 58 | } 59 | 60 | $raw = substr($raw, 0, -2); 61 | 62 | return parent::newQuery()->addSelect("{$this->getTable()}.*", DB::raw($raw)); 63 | } 64 | 65 | public function getLocationCastedAttributes(): Collection 66 | { 67 | return collect($this->getCasts())->filter(fn ($cast) => $cast === LocationCast::class)->keys(); 68 | } 69 | 70 | private function selectDistanceToMysqlAndPostgres(Builder $query, string $column, Point $point): Builder 71 | { 72 | return $query->selectRaw( 73 | "ST_Distance(ST_SRID({$column}, ?), ST_SRID(Point(?, ?), ?)) as distance", 74 | [ 75 | $point->getSrid(), 76 | $point->getLng(), 77 | $point->getLat(), 78 | $point->getSrid(), 79 | ] 80 | ); 81 | } 82 | 83 | private function selectDistanceToMariaDb(Builder $query, string $column, Point $point): Builder 84 | { 85 | return $query->selectRaw( 86 | "ST_Distance(ST_SRID({$column}), ST_SRID(Point(?, ?))) as distance", 87 | [ 88 | $point->getLng(), 89 | $point->getLat(), 90 | ] 91 | ); 92 | } 93 | 94 | private function withinDistanceToMysqlAndPostgres(Builder $query, string $column, Point $point, int $distance): Builder 95 | { 96 | return $query 97 | ->whereRaw("ST_AsText({$column}) != ?", [ 98 | 'POINT(0 0)', 99 | ]) 100 | ->whereRaw( 101 | "ST_Distance(ST_SRID({$column}, ?), ST_SRID(Point(?, ?), ?)) <= ?", 102 | [ 103 | ...[ 104 | $point->getSrid(), 105 | $point->getLng(), 106 | $point->getLat(), 107 | $point->getSrid(), 108 | ], 109 | $distance, 110 | ] 111 | ); 112 | } 113 | 114 | private function withinDistanceToMariaDb(Builder $query, string $column, Point $point, int $distance): Builder 115 | { 116 | return $query 117 | ->whereRaw("ST_AsText({$column}) != ?", [ 118 | 'POINT(0 0)', 119 | ]) 120 | ->whereRaw( 121 | "ST_Distance(ST_SRID({$column}), ST_SRID(Point(?, ?))) <= ?", 122 | [ 123 | $point->getLng(), 124 | $point->getLat(), 125 | $distance, 126 | ] 127 | ); 128 | } 129 | 130 | private function orderByDistanceToMysqlAndPostgres(Builder $query, string $column, Point $point, string $direction = 'asc'): Builder 131 | { 132 | return $query->orderByRaw( 133 | "ST_Distance(ST_SRID({$column}, ?), ST_SRID(Point(?, ?), ?)) " . $direction, 134 | [ 135 | $point->getSrid(), 136 | $point->getLng(), 137 | $point->getLat(), 138 | $point->getSrid(), 139 | ] 140 | ); 141 | } 142 | 143 | private function orderByDistanceToMariaDb(Builder $query, string $column, Point $point, string $direction = 'asc'): Builder 144 | { 145 | return $query->orderByRaw( 146 | "ST_Distance(ST_SRID({$column}), ST_SRID(Point(?, ?))) " . $direction, 147 | [ 148 | $point->getLng(), 149 | $point->getLat(), 150 | ] 151 | ); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/Types/Point.php: -------------------------------------------------------------------------------- 1 | lat = $lat; 20 | $this->lng = $lng; 21 | 22 | $this->srid = is_null($srid) 23 | ? config('laravel-spatial.default_srid') ?? 0 24 | : $srid; 25 | 26 | $this->wktOptions = config('laravel-spatial.with_wkt_options', true) === true 27 | ? ', \'axis-order=long-lat\'' 28 | : ''; 29 | } 30 | 31 | public function getLat(): float 32 | { 33 | return $this->lat; 34 | } 35 | 36 | public function getLng(): float 37 | { 38 | return $this->lng; 39 | } 40 | 41 | public function getSrid(): int 42 | { 43 | return $this->srid; 44 | } 45 | 46 | public function toWkt(): string 47 | { 48 | return sprintf('POINT(%s)', $this->toPair()); 49 | } 50 | 51 | public function toPair(): string 52 | { 53 | return "{$this->getLng()} {$this->getLat()}"; 54 | } 55 | 56 | public function toGeomFromText(): string 57 | { 58 | return "ST_GeomFromText('{$this->toWkt()}', {$this->getSrid()}{$this->wktOptions})"; 59 | } 60 | 61 | public function toArray(): array 62 | { 63 | return [ 64 | 'lat' => $this->lat, 65 | 'lng' => $this->lng, 66 | 'srid' => $this->srid, 67 | ]; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /tests/HasSpatialTest.php: -------------------------------------------------------------------------------- 1 | getLocationCastedAttributes()->first(); 17 | 18 | // Act 19 | $query = $address->selectDistanceTo($castedAttr, new Point()); 20 | 21 | // Assert 22 | $this->assertEquals( 23 | expected: "select `addresses`.*, CONCAT(ST_AsText(addresses.$castedAttr, 'axis-order=long-lat'), ',', ST_SRID(addresses.$castedAttr)) as $castedAttr, ST_Distance(ST_SRID($castedAttr, ?), ST_SRID(Point(?, ?), ?)) as distance from `addresses`", 24 | actual: $query->toSql() 25 | ); 26 | } 27 | 28 | #[Test] 29 | public function it_generates_sql_query_for_withinDistanceTo_scope(): void 30 | { 31 | // 1. Arrange 32 | $address = new Address(); 33 | $castedAttr = $address->getLocationCastedAttributes()->first(); 34 | 35 | // 2. Act 36 | $query = $address->withinDistanceTo($castedAttr, new Point(), 10000); 37 | 38 | // 3. Assert 39 | $this->assertEquals( 40 | expected: "select `addresses`.*, CONCAT(ST_AsText(addresses.$castedAttr, 'axis-order=long-lat'), ',', ST_SRID(addresses.$castedAttr)) as $castedAttr from `addresses` where ST_AsText(location) != ? and ST_Distance(ST_SRID($castedAttr, ?), ST_SRID(Point(?, ?), ?)) <= ?", 41 | actual: $query->toSql() 42 | ); 43 | } 44 | 45 | #[Test] 46 | public function it_generates_sql_query_for_orderByDistanceTo_scope(): void 47 | { 48 | // 1. Arrange 49 | $address = new Address(); 50 | $castedAttr = $address->getLocationCastedAttributes()->first(); 51 | 52 | // 2. Act 53 | $queryForAsc = $address->orderByDistanceTo($castedAttr, new Point()); 54 | $queryForDesc = $address->orderByDistanceTo($castedAttr, new Point(), 'desc'); 55 | 56 | // 3. Assert 57 | $this->assertEquals( 58 | expected: "select `addresses`.*, CONCAT(ST_AsText(addresses.$castedAttr, 'axis-order=long-lat'), ',', ST_SRID(addresses.$castedAttr)) as $castedAttr from `addresses` order by ST_Distance(ST_SRID($castedAttr, ?), ST_SRID(Point(?, ?), ?)) asc", 59 | actual: $queryForAsc->toSql() 60 | ); 61 | 62 | $this->assertEquals( 63 | expected: "select `addresses`.*, CONCAT(ST_AsText(addresses.$castedAttr, 'axis-order=long-lat'), ',', ST_SRID(addresses.$castedAttr)) as $castedAttr from `addresses` order by ST_Distance(ST_SRID($castedAttr, ?), ST_SRID(Point(?, ?), ?)) desc", 64 | actual: $queryForDesc->toSql() 65 | ); 66 | } 67 | 68 | #[Test] 69 | public function it_generates_sql_query_for_location_casted_attributes(): void 70 | { 71 | // 1. Arrange 72 | $address = new Address(); 73 | $castedAttr = $address->getLocationCastedAttributes()->first(); 74 | 75 | // 2. Act & Assert 76 | $this->assertEquals( 77 | expected: "select `addresses`.*, CONCAT(ST_AsText(addresses.$castedAttr, 'axis-order=long-lat'), ',', ST_SRID(addresses.$castedAttr)) as $castedAttr from `addresses`", 78 | actual: $address->query()->toSql() 79 | ); 80 | } 81 | 82 | #[Test] 83 | public function it_returns_location_casted_attributes(): void 84 | { 85 | // 1. Arrange 86 | $address = new Address(); 87 | 88 | // 2. Act 89 | $locationCastedAttributres = $address->getLocationCastedAttributes(); 90 | 91 | // 3. Assert 92 | $this->assertEquals(collect(['location']), $locationCastedAttributres); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /tests/LocationCastTest.php: -------------------------------------------------------------------------------- 1 | expectException(InvalidArgumentException::class); 23 | 24 | // 3. Act 25 | $address->location = 'dummy'; 26 | } 27 | 28 | #[Test] 29 | public function it_can_set_the_casted_attribute_to_a_point(): void 30 | { 31 | // 1. Arrange 32 | $address = new Address(); 33 | $point = new Point(27.1234, 39.1234); 34 | 35 | $cast = new LocationCast(); 36 | 37 | // 2. Act 38 | $response = $cast->set($address, 'location', $point, $address->getAttributes()); 39 | 40 | // 3. Assert 41 | $this->assertEquals(DB::raw("ST_GeomFromText('{$point->toWkt()}', 4326, 'axis-order=long-lat')"), $response); 42 | } 43 | 44 | #[Test] 45 | public function it_can_set_the_casted_attribute_to_a_point_with_srid(): void 46 | { 47 | // 1. Arrange 48 | $address = new Address(); 49 | $point = new Point(27.1234, 39.1234, 4326); 50 | 51 | $cast = new LocationCast(); 52 | 53 | // 2. Act 54 | $response = $cast->set($address, 'location', $point, $address->getAttributes()); 55 | 56 | // 3. Assert 57 | $this->assertEquals(DB::raw("ST_GeomFromText('{$point->toWkt()}', {$point->getSrid()}, 'axis-order=long-lat')"), $response); 58 | } 59 | 60 | #[Test] 61 | public function it_can_get_a_casted_attribute(): void 62 | { 63 | // 1. Arrange 64 | $address = new Address(); 65 | $point = new Point(27.1234, 39.1234); 66 | 67 | // 2. Act 68 | $address->location = $point; 69 | $address->save(); 70 | 71 | // 3. Assert 72 | $this->assertInstanceOf(Point::class, $address->location); 73 | $this->assertEquals($point->getLat(), $address->location->getLat()); 74 | $this->assertEquals($point->getLng(), $address->location->getLng()); 75 | $this->assertEquals($point->getSrid(), $address->location->getSrid()); 76 | } 77 | 78 | #[Test] 79 | public function it_can_get_a_casted_attribute_using_expression(): void 80 | { 81 | // 1. Arrange 82 | $address = new Address(); 83 | $point = new Point(27.1234, 39.1234); 84 | 85 | // 2. Act 86 | $cast = new LocationCast(); 87 | $result = $cast->get($address, 'location', new Expression($point->toGeomFromText()), $address->getAttributes()); 88 | 89 | // 3. Assert 90 | $this->assertInstanceOf(Point::class, $result); 91 | $this->assertEquals($point->getLat(), $result->getLat()); 92 | $this->assertEquals($point->getLng(), $result->getLng()); 93 | $this->assertEquals($point->getSrid(), $result->getSrid()); 94 | } 95 | 96 | #[Test] 97 | public function it_returns_null_if_the_value_of_the_casted_column_is_null(): void 98 | { 99 | // 1. Arrange 100 | $address = new Address(); 101 | 102 | // 2. Act 103 | $address->save(); 104 | 105 | // 3. Assert 106 | $this->assertNull($address->location); 107 | } 108 | 109 | #[Test] 110 | public function it_can_serialize_a_casted_attribute(): void 111 | { 112 | // 1. Arrange 113 | $address = new Address(); 114 | $point = new Point(27.1234, 39.1234); 115 | 116 | // 2. Act 117 | $address->location = $point; 118 | $address->save(); 119 | 120 | // 3. Assert 121 | $array = $address->toArray(); 122 | $this->assertIsArray($array); 123 | $this->assertArrayHasKey('location', $array); 124 | $this->assertArrayHasKey('lat', $array['location']); 125 | $this->assertArrayHasKey('lng', $array['location']); 126 | $this->assertArrayHasKey('srid', $array['location']); 127 | 128 | $this->assertJson($address->toJson()); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /tests/PointTest.php: -------------------------------------------------------------------------------- 1 | assertSame(expected: $lat, actual: $point->getLat()); 26 | $this->assertSame(expected: $lng, actual: $point->getLng()); 27 | $this->assertSame(expected: $srid, actual: $point->getSrid()); 28 | } 29 | 30 | #[Test] 31 | public function it_returns_default_lat_lng_and_srid_if_they_are_not_given_in_the_constructor(): void 32 | { 33 | // 1. Act 34 | $point = new Point(); 35 | 36 | // 2. Assert 37 | $this->assertSame(expected: 0.0, actual: $point->getLat()); 38 | $this->assertSame(expected: 0.0, actual: $point->getLng()); 39 | $this->assertSame(expected: 4326, actual: $point->getSrid()); 40 | } 41 | 42 | #[Test] 43 | public function it_returns_default_srid_in_config_if_it_is_not_null(): void 44 | { 45 | // 1. Arrange 46 | Config::set('laravel-spatial.default_srid', 4326); 47 | 48 | // 2. Act 49 | $point = new Point(); 50 | 51 | // 3. Assert 52 | $this->assertSame(expected: 0.0, actual: $point->getLat()); 53 | $this->assertSame(expected: 0.0, actual: $point->getLng()); 54 | $this->assertSame(expected: 4326, actual: $point->getSrid()); 55 | } 56 | 57 | #[Test] 58 | public function it_returns_point_as_wkt(): void 59 | { 60 | // 1. Arrange 61 | $point = new Point(25.1515, 36.1212, 4326); 62 | 63 | // 2. Act 64 | $wkt = $point->toWkt(); 65 | 66 | // 3. Assert 67 | $this->assertSame("POINT({$point->getLng()} {$point->getLat()})", $wkt); 68 | } 69 | 70 | #[Test] 71 | public function it_returns_point_as_pair(): void 72 | { 73 | // 1. Arrange 74 | $point = new Point(25.1515, 36.1212, 4326); 75 | 76 | // 2. Act 77 | $pair = $point->toPair(); 78 | 79 | // 3. Assert 80 | $this->assertSame("{$point->getLng()} {$point->getLat()}", $pair); 81 | } 82 | 83 | #[Test] 84 | public function it_returns_points_as_geometry(): void 85 | { 86 | // 1. Arrange 87 | $point = new Point(25.1515, 36.1212, 4326); 88 | 89 | // 2. Act 90 | $geometry = $point->toGeomFromText(); 91 | 92 | // 3. Assert 93 | $this->assertSame("ST_GeomFromText('{$point->toWkt()}', {$point->getSrid()}, 'axis-order=long-lat')", $geometry); 94 | } 95 | 96 | #[Test] 97 | public function it_returns_points_as_array(): void 98 | { 99 | // 1. Arrange 100 | $point = new Point(25.1515, 36.1212, 4326); 101 | 102 | // 2. Act 103 | $array = $point->toArray(); 104 | 105 | $expected = [ 106 | 'lat' => $point->getLat(), 107 | 'lng' => $point->getLng(), 108 | 'srid' => $point->getSrid(), 109 | ]; 110 | 111 | // 3. Assert 112 | $this->assertSame($expected, $array); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | loadMigrationsFrom(__DIR__ . '/database/migrations'); 12 | } 13 | 14 | protected function getPackageProviders($app): array 15 | { 16 | return [ 17 | LaravelSpatialServiceProvider::class, 18 | ]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/TestModels/Address.php: -------------------------------------------------------------------------------- 1 | LocationCast::class, 32 | ]; 33 | } 34 | -------------------------------------------------------------------------------- /tests/database/migrations/0000_00_00_000000_create_addresses_table.php: -------------------------------------------------------------------------------- 1 | id(); 13 | $table->geography('location', subtype: 'point')->nullable(); 14 | $table->timestamps(); 15 | }); 16 | } 17 | 18 | public function down(): void 19 | { 20 | Schema::dropIfExists('addresses'); 21 | } 22 | }; 23 | --------------------------------------------------------------------------------