简体   繁体   中英

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?

You can create a middleware for the logged in user language.

public function handle($request, Closure $next)
{   

    if (!Auth::check()) {
      return redirect('/')->with('Success','You have successfully logged out');    
    }

    $user = \Auth::user();

    $language =  $user->languages()->where('language_id', $user->language_id);

    $request->attributes->add([
        'user_language' => $language
    ]);

    $next($request);
}

You can get this data after middleware like

$request->attributes->get('user_language');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM