How to setup conditional relationship on Eloquent

Ju Nogueira picture Ju Nogueira · Apr 27, 2017 · Viewed 10k times · Source

I have this (simplified) table structure:

users
- id
- type (institutions or agents)

institutions_profile
- id
- user_id
- name

agents_profile
- id
- user_id
- name

And I need to create a profile relationship on the Users model, but the following doesn't work:

class User extends Model
{
    public function profile()
    {
        if ($this->$type === 'agents')
            return $this->hasOne('AgentProfile');
        else
            return $this->hasOne('InstitutionProfile');
    }    
}

How could I achieve something like that?

Answer

oseintow picture oseintow · Apr 28, 2017

Lets take a different approach in solving your problem. First lets setup relationship for the various models respectively.

class User extends Model
{
    public function agentProfile()
    {
        return $this->hasOne(AgentProfile::class);
    }    

    public function institutionProfile()
    {
        return $this->hasOne(InstitutionProfile::class);
    }

    public function schoolProfile()
    {
        return $this->hasOne(SchoolProfile::class);
    }

    public function academyProfile()
    {
        return $this->hasOne(AcademyProfile::class);
    }

    // create scope to select the profile that you want
    // you can even pass the type as a second argument to the 
    // scope if you want
    public function scopeProfile($query)
    {
        return $query
              ->when($this->type === 'agents',function($q){
                  return $q->with('agentProfile');
             })
             ->when($this->type === 'school',function($q){
                  return $q->with('schoolProfile');
             })
             ->when($this->type === 'academy',function($q){
                  return $q->with('academyProfile');
             },function($q){
                 return $q->with('institutionProfile');
             });
    }
}

Now you can access your profile like this

User::profile()->first();

This should give you the right profile. Hope it helps.