How to setup conditional relationship on Eloquent How to setup conditional relationship on Eloquent laravel laravel

How to setup conditional relationship on Eloquent


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.


you can do this by use another method please check this:

a blog Post and Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation allows you to have a single list of unique tags that are shared across blog posts and videos. First, let's examine the table structure:

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations


Looks like that should be $this->type rather than $this->$type - since type is a property, not a variable.