Level 36
@wildwestriverrider I found only this method
DB::statement('UPDATE table SET column = POINT(?, ?) WHERE id=?', [111, 222, 1]);
How do you insert/update data for the new point type column in Laravel 5.5?
@wildwestriverrider I found only this method
DB::statement('UPDATE table SET column = POINT(?, ?) WHERE id=?', [111, 222, 1]);
This is what I am doing for now.
trait HasPosition
{
/**
* @param Point $point
*/
public function setPositionAttribute(Point $point)
{
$query = "GeomFromText('POINT($point->x $point->y)')";
$this->attributes['position'] = \DB::raw($query);
}
/**
* @param string $value
* @return Point
*/
public function getPositionAttribute($value)
{
// cleanup the database response into a Point
$response = explode(
' ',
str_replace(
[
"GeomFromText('",
"'",
'POINT(',
')'
],
'',
$value
)
);
return new Point($response[0], $response[1]);
}
public function newQuery($excludeDeleted = true)
{
$raw = ' astext(position) as position ';
return parent::newQuery($excludeDeleted)->addSelect('*', \DB::raw($raw));
}
}
With a simple Point class
class Point
{
public $x;
public $y;
public function __construct($x = null, $y = null)
{
$this->x = is_numeric($x) ? floatval($x) : $x;
$this->y = is_numeric($y) ? floatval($y) : $y;
}
}
Using a dedicated Point class obviously looks the best way to go, but how does this work in inserting and retrieving?
I mean, can i do something like this?
$city = City::create();
$city->coordinates = new Point(2,3);
$city->save();
Or something like this?
$city = City::find(1);
Point $coordinates = $city->coordinates;
Will it work out of the box?
The question is for a long time ago, and I wonder is there any convenient way to handle geo points these days?
@tuytoosh I was just looking for the same but it seem only with an additional package laravel-eloquent-spatial has a point class
Please or to participate in this conversation.