1 month ago

Dynamic/conditional relationships

Posted 1 month ago by schwartzmj

My app is fairly simple, so I decided to hardcode 3 different roles onto users: 'family', 'agency', and 'admin'.

  • family users hasMany applications
  • agency users hasManyThrough applications, through a family user
  • admin do NOT have any applications

Here's how I've been doing the relationship (which is probably wrong?):

    public function applications()
        if ($this->role === 'family') {
            return $this->hasMany(Application::class, 'family_id');

        if ($this->role === 'agency') {
            return $this->hasManyThrough(Application::class, User::class, 'agency_id', 'family_id');

        throw new \Exception('User is not an "agency" or a "family", so has no Applications.');

I'm now encountering an issue where I want to query all families and then eager load their applications. Something like this:

                $this->families = User::where('role', 'family')

This query results in the error User is not an "agency" or a "family", so has no Applications from my applications() relationship.

Obviously I'm probably doing something terribly wrong here and I've read through the docs, but I'm not sure how to proceed next. Does anybody have suggestions?

Please sign in or create an account to participate in this conversation.