laravel icon indicating copy to clipboard operation
laravel copied to clipboard

Docs need some guidance on writing custom fields

Open lindyhopchris opened this issue 3 years ago • 1 comments

There's nothing in the fields chapter of the docs about how to write your own fields. This probably needs documenting.

Raised because someone asked on Slack about supporting spatial fields; they're using this package: https://github.com/grimzy/laravel-mysql-spatial

There's no where in the docs to point them to how to write their own field.

lindyhopchris avatar Feb 09 '22 20:02 lindyhopchris

This is what works for now;

<?php

namespace App\JsonApi\V1\Fields;

use LaravelJsonApi\Eloquent\Fields\Attribute;
use Illuminate\Database\Eloquent\Model;
use Grimzy\LaravelMysqlSpatial\Types\Point as GeoPoint;


class Point extends Attribute
{
    /**
     * Create a string attribute.
     *
     * @param  string      $fieldName
     * @param  string|null $column
     * @return Str
     */
    public static function make(string $fieldName, string $column = null): self
    {
        return new self($fieldName, $column);
    }

    /**
     *  Assert that the attribute JSON value is as expected.
     *
     * @param  [type] $value
     * @return void
     */
    protected function assertValue($value): void
    {
        if (!is_null($value) && !is_string($value)) {
            throw new \UnexpectedValueException(
                sprintf(
                    'Expecting the value of attribute %s to be a GeoPoint.',
                    $this->name()
                )
            );
        }
    }

    public function fill(Model $model, $value, array $validatedData): void
    {
        $column = $this->column() ?: $model->getRouteKeyName();
        $coordinates = $value['coordinates'];

        $model->{$column} = new GeoPoint($coordinates[0], $coordinates[1]);
    }
}

tdwesten avatar Feb 12 '22 10:02 tdwesten