try field attributes as 'float (10,6)' or 'int(10,6)' for longitude and latitude separately eg. longitude float(10,6) latitude float(10,6)
Handle mySql POINT fields in Laravel
Hi!
in my project I have a model User, which uses a POINT data type field. However, MySQL store this data as [GEOMETRY - 25 B], which Eloquent sees as a Binary data, therefore I am unable to echo it in a readable way. I have found the following solution, which works:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
// snippet
protected $geometry = ['latlong'];
protected $geometryAsText = true;
public function newQuery($excludeDeleted = true)
{
if (!empty($this->geometry) && $this->geometryAsText === true)
{
$raw = '';
foreach ($this->geometry as $column)
{
$raw .= 'AsText(`' . $this->table . '`.`' . $column . '`) as `' . $column . '`, ';
}
$raw = substr($raw, 0, -2);
return parent::newQuery($excludeDeleted)->addSelect('*', DB::raw($raw));
}
return parent::newQuery($excludeDeleted);
}
}
If I understand correctly, this code convert into a text the relevant field each time I make a query (e.g.: 'POINT(37.774929 -122.419415)'). However, I am not able to understand what's actually going on, I tried to read the documentation to no avail. In particular, what does Model::newQuery do? Why we need a $geometryAsText attribute, which seems to me be alway true?
Thank you.
Please or to participate in this conversation.