Laravel Spatial
Laravel package to work with geospatial data types and functions.
For now it supports only MySql Spatial Data Types and Functions.
Supported data types:
Point
Available Scopes:
withinDistanceTo($column, $coordinates, $distance)
selectDistanceTo($column, $coordinates)
orderByDistanceTo($column, $coordinates, 'asc')
Installation
You can install the package via composer:
composer require tarfin-labs/laravel-spatial
Usage
Generate a new model with a migration file:
php artisan make:model Address --migration
To avoid Doctrine\DBAL\Exception : Unknown database type point requested, Doctrine\DBAL\Platforms\MySQL80Platform may not support it.
exception, extend the migration file from TarfinLabs\LaravelSpatial\Migrations\SpatialMigration
and add a spatial column. It just adds point
type to Doctrine mapped types.
use TarfinLabs\LaravelSpatial\Migrations\SpatialMigration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends SpatialMigration {
public function up(): void
{
Schema::create('addresses', function (Blueprint $table) {
$table->point('location');
$table->spatialIndex('location');
})
}
}
Fill the $fillable
, $casts
arrays in the model:
use Illuminate\Database\Eloquent\Model;
use TarfinLabs\LaravelSpatial\Casts\LocationCast;
use TarfinLabs\LaravelSpatial\Traits\HasSpatial;
class Address extends Model {
use HasSpatial;
protected $fillable = [
'id',
'name',
'address',
'location',
];
protected array $casts = [
'location' => LocationCast::class
];
}
Filter addresses within 10 km of the given coordinate:
use TarfinLabs\LaravelSpatial\Types\Point;
use App\Models\Address;
Address::query()
->withinDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331), 10000)
->get();
Select distance to given coordinate as meter:
use TarfinLabs\LaravelSpatial\Types\Point;
use App\Models\Address;
Address::query()
->selectDistanceTo('location', new Point(lat: 25.45634, lng: 35.54331))
->get();
Get latitude and longitude of the location:
use App\Models\Address;
$address = Address::find(1);
$address->location; // TarfinLabs\LaravelSpatial\Types\Point
$address->location->getLat();
$address->location->getLng();
Create a new address with location:
use App\Models\Address;
Address::create([
'name' => 'Bag End',
'address' => '1 Bagshot Row, Hobbiton, Shire',
'location' => new Point(lat: 25.45634, lng: 35.54331),
]);
Testing
composer test
Todo
- Proper documentation.
- Missing tests.
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
Laravel Package Boilerplate
This package was generated using the Laravel Package Boilerplate.