5.5 Point type column

Published 9 months ago by wildwestriverrider

How do you insert/update data for the new point type column in Laravel 5.5?

Dry7
Dry7
9 months ago (151,880 XP)

@wildwestriverrider I found only this method

DB::statement('UPDATE table SET column = POINT(?, ?) WHERE id=?', [111, 222, 1]);
wildwestriverrider

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));
    }
}
wildwestriverrider

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;
    }
}
christian.giupponi

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?

Please sign in or create an account to participate in this conversation.