2

I'm using Eloquent to get some data from the database. My database has a column that uses the POINT data type. The columns have values such as POINT(52.45083 -1.930546).

I require this data from the database which I then return as JSON. Including the POINT data. But, Eloquent returns it in the following form:

array(7) {
    ["id"]=>
    int(2)
    ["city_id"]=>
    int(1)
    ["image"]=>
    NULL
    ["name"]=>
    string(20) "University of London"
    ["geo_coords"]=>
    string(25) "ͯ���I@�h�^`V��"
    ["created_at"]=>
    string(19) "2017-01-11 10:53:46"
    ["updated_at"]=>
    NULL
  }

Why is this?

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121
  • 1
    Not sure if eloquent supports POINT data. https://laravel.com/docs/5.0/eloquent#accessors-and-mutators may be a nice way to transform your model. – apokryfos Feb 01 '17 at 21:33
  • may help: http://stackoverflow.com/questions/30682538/handling-mysql-spatial-datatypes-in-laravel-eloquent-orm –  Feb 01 '17 at 21:34

1 Answers1

3

Add the following code to your model.

protected $geofields = array('geo_coords');

Then add setters and getters for geo_coords

Setters

public function setGeoCoordsAttribute($value) {
    $this->attributes['geo_coords'] = DB::raw("POINT($value)");
}

Getters

public function getGeoCoordsAttribute($value) {
    return str_replace(['POINT(', ')', ' '], ['', '', ','], $value);
}

Now while querying, you will point value as simple string with lat and long.

public function newQuery($excludeDeleted = true)
{
    $raw='';
    foreach($this->geofields as $column){
        $raw .= ' astext('.$column.') as '.$column.' ';
    }

    return parent::newQuery($excludeDeleted)->addSelect('*',DB::raw($raw));
}
Saravanan Sampathkumar
  • 3,201
  • 1
  • 20
  • 46