Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheCrownPrince's avatar

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.

0 likes
3 replies
Arushad's avatar

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)

TheCrownPrince's avatar

Thanks! Of course, by using two fields there are no issues. But I think it could usefull to understand how Laravel works with Point data type.

Čamo's avatar

Any solution. Point database type throws me and error from JsonResponse()

Please or to participate in this conversation.