vendredi 9 décembre 2016

Always eager load relation when using a trait in eloquent model

I'm providing a HasTranslation-Trait for any of my eloquent models. All models using this trait will receive a one-to-many-relation like this (where you can see my basic Model to ModelLanguages relations):

public function languages()
{
    return $this->hasMany(get_class($this).'Lang', 'master_id', 'id');
}

What I want to do is:

Always eager load a "hasOne"-relationship with the translation of current user's language. So whenever the user is logged in, my models should have something like $model->userLanguage being eager loaded and is of type ModelLang.

This looks like this and works great:

public function userLanguage()
{
    $user = \Auth::user();

    if (!$user)
    {
        throw new \Exception(__CLASS__.': userLanguage not available because there is no session');
    }

    return $this->hasOne(get_class($this).'Lang', 'master_id', 'id')->where('language_id', $user->language_id);
}

I'm struggling with the possibility to automatically (eager) load this relations for all models by just including this trait.

What I've tried so far

  1. Use a constructor within the trait: Can work, but no good idea, because this can collide with other trait's contructor. Basically I'd confirm the statement: Do not use the constructor in any trait.

  2. Use your boot-Trait method (bootHasTranslation) but there I do not have the concrete object to call load or with method on. I did not find any hook into the instantiated eloquent model where I want to add my relation to eager load

Any ideas? Is there something obvious I've overlooked here?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire