Discount !! E-commerce App With Backend Source Code Video and Voice Chatting App Firebase Chatting App Source Code Complete Gym App BLoC State Management Source Code Complete Study App Buy Ticket Booking App Source Code Payment App Buy Travel App With Backend Source Code Complete Chat App Udemy Course Special Offer Discount !! Online Learning Course App (BLoC) Discount !! Online Learning Course App (Riverpod) Discount !! Online Learning Course App (Getx)
Here we will see how to work with geometry and coordinates using SpatialTrait, Point, Polygon and LineString in Laravel.
There are packages for it, and just install the package using composer.
composer require grimzy/laravel-mysql-spatial:^4.0
After getting the package you need to publish it, in general it should be auto published. If not add this in config/app.php
'providers' => [
/*
* Package Service Providers...
*/
Grimzy\LaravelMysqlSpatial\SpatialServiceProvider::class,
],
Then you are ready to use spatial coordinates and all the other classes.
Complete code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Grimzy\LaravelMysqlSpatial\Types\Polygon;
use Grimzy\LaravelMysqlSpatial\Types\LineString;
class Zone extends Model
{
use HasFactory;
use SpatialTrait;
protected $spatialFields = [
'coordinates'
];
public function orders()
{
return $this->hasManyThrough(Order::class);
}
public function deliverymen()
{
return $this->hasMany(DeliveryMan::class);
}
public function scopeActive($query)
{
return $query->where('status', '=', 1);
}
public function getCoordinatesAttribute($value)
{
if($value){
$data_str = "";
foreach($value as $coord)
{
foreach ($coord as $val){
$data_str = $data_str."({$val->getlat()},{$val->getlng()}),";
}
}
return substr($data_str,0,-1);
}
return $value;
}
public function setCoordinatesAttribute($value)
{
$lastcord = [];
$polygon= [];
foreach(explode('),(',trim($value,'()')) as $index=>$single_array){
if($index == 0)
{
$lastcord = explode(',',$single_array);
}
$coords = explode(',',$single_array);
$polygon[] = new Point($coords[0], $coords[1]);
}
$polygon[] = new Point($lastcord[0], $lastcord[1]);
$coordinates = new Polygon([new LineString($polygon)]);
$this->attributes['coordinates'] = $coordinates;
}
}