Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only load includes which correspond to actual relationships (fix #1096) #1758

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

blmage
Copy link

@blmage blmage commented Oct 19, 2020

In my use case, I have a Language model, whose display name can be translated into any other language:

/**
 * @property int $id
 * @property string $code
 * @property-read string $self_display_name
 */
class Language extends RestfulModel
{
    protected $appends = [
        'self_display_name',
    ];

    /**
     * Returns the own displayable name of the language.
     *
     * @return string
     */
    public function getSelfDisplayNameAttribute(): string
    {
        return $this->getDisplayName($this->code);
    }

    /**
     * Returns a displayable name for the language, translated into another given language.
     *
     * @param string $languageCode
     * @return string
     */
    public function getDisplayName(string $languageCode): string
    {
        return Str::ucfirst(Str::lower(\Locale::getDisplayLanguage($this->code, $languageCode)));
    }
}

and a transformer that allows the client to specify the languages into which the display names should be translated:

class LanguageTransformer extends BaseTransformer
{
    protected $availableIncludes = [
        'displayNames',
    ];

    /**
     * @param Language $language
     * @param ParamBag|null $params
     * @return ResourceAbstract
     */
    public function includeDisplayNames(Language $language, ParamBag $params = null)
    {
        if (null === $params) {
            return $this->null();
        }

        $displayNames = [];
        $languageCodes = array_filter(array_map('trim', (array) $params->get('languages')));

        foreach ($languageCodes as $languageCode) {
            $displayNames[$languageCode] = $language->getDisplayName($languageCode);
        }

        return $this->primitive($displayNames);
    }
}

But because displayNames is not a relationship, queries fail whenever the corresponding include is requested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants