Last active
February 20, 2021 04:17
-
-
Save tanthammar/52d222fb5acf0a1cfc35f3ab9a8c1622 to your computer and use it in GitHub Desktop.
Auto generate spatial point when creating or updating a Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use App\Helpers\GeoHelper; | |
use Grimzy\LaravelMysqlSpatial\Types\Point; | |
trait AutoGeneratesPosition | |
{ | |
protected static function bootHasPosition() | |
{ | |
static::creating(function ($model) { | |
if ( | |
filled($model->latitude) && | |
filled($model->longitude) && | |
GeoHelper::spatialPointCoordsAreValid((float)$model->latitude, (float)$model->longitude) | |
) { | |
$model->position = new Point($model->latitude, $model->longitude); // (lat, lng); | |
} | |
}); | |
static::updated(function ($model) { | |
if ( | |
filled($model->latitude) && | |
filled($model->longitude) && | |
GeoHelper::spatialPointCoordsAreValid((float)$model->latitude, (float)$model->longitude) | |
) { | |
$model->position = new Point($model->latitude, $model->longitude); // (lat, lng); | |
} | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
class GeoHelper | |
{ | |
public static function spatialPointCoordsAreValid(float $lat, float $long): bool | |
{ | |
return ($lat >= -90 && $lat <= 90 && $long >= -180 && $long <= 180); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment