laravellaravel-8voyager

Get geometry value


Use Laravel 8 + Voyager + Swagger. As in instruction https://voyager-docs.devdojo.com/v/1.1/customization/coordinates - Use geometry type for points column

Schema::create('offices', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address')->nullable();
            $table->geometry('points')->nullable();
            $table->timestamps();
        });

But in API response got an error -

enter image description here

mb_convert_encoding(\DB::raw($this->attributes['points']), 'UTF-8'); - return 
"points": "\u0000\u0000\u0000\u0000\u0001\u0001\u0000\u0000\u0000??\u0010??bR??Ng???D@", 

Please help return the correct value.


Solution

  • It is being returned a Well-Known-Binary in the response? I never worked with Voyager or Swagger, but, to work with coordinates in geometry fields in Laravel, one option to use is Accessors/Mutators.

    A easy way to get the coordinates array is get the field as a GeoJSON, with the ST_AsGeoJSON function, and use a json_decode to return the coordinates field.

    Something like this could return the coordinates:

    public function getPointsAttribute($value)
        {
            $result = DB::table('offices')
                ->select(DB::raw('ST_AsGeoJSON(points) as points'))
                ->where('id', $this->id)
                ->first();
    
            $geojson = \json_decode($result->points);
            return $geojson->coordinates;
        }