laravel-json-api / laravel

JSON:API for Laravel applications
MIT License
551 stars 42 forks source link

Use with spatie laravel-translatable #226

Closed invaders-xx closed 1 year ago

invaders-xx commented 1 year ago

My model implements laravel-translatable and I have issue with API for Schema. I use ArrayHash for those translatable fieds but I got a exception : "LogicException: Unable to encode compound document. ". If I remove the spatie HasTranslations from Model it works. Is there a simple way to make those 2 packages working together ?

Many thanks in advance for your help.

invaders-xx commented 1 year ago

I solved it by creating my own API resource

lindyhopchris commented 1 year ago

Just FYI the exception LogicException: Unable to encode compound document. has a previous exception, which is the one that caused the encoding to fail. So checking that previous exception will tell you what the problem is.

invaders-xx commented 1 year ago

@lindyhopchris I don't see any other exception in the error message.

kitro commented 1 year ago

Using https://laraveljsonapi.io/docs/1.0/schemas/sorting.html#writing-sort-fields can handle that. For example, we have a Translatable Country model sorting it by the name JSON field like this:

<?php

namespace App\JsonApi\Sorting\Country;

use LaravelJsonApi\Eloquent\Contracts\SortField;

class CountryNameSort implements SortField
{

    /**
     * @var string
     */
    private string $name;

    /**
     * Create a new sort field.
     *
     * @param string $name
     * @param string|null $column
     * @return CountryNameSort
     */
    public static function make(string $name): self
    {
        return new static($name);
    }

    /**
     * CountryNameSort constructor.
     *
     * @param string $name
     */
    public function __construct(string $name)
    {
        $this->name = $name;
    }

    /**
     * Get the name of the sort field.
     *
     * @return string
     */
    public function sortField(): string
    {
        return $this->name;
    }

    /**
     * Apply the sort order to the query.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $direction
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function sort($query, string $direction = 'asc')
    {
        return $query->orderBy('name->en', $direction);
    }
}