Skip to content

Instantly share code, notes, and snippets.

@tanthammar
Last active February 20, 2021 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tanthammar/52d222fb5acf0a1cfc35f3ab9a8c1622 to your computer and use it in GitHub Desktop.
Save tanthammar/52d222fb5acf0a1cfc35f3ab9a8c1622 to your computer and use it in GitHub Desktop.
Auto generate spatial point when creating or updating a Model
<?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);
}
});
}
}
<?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