3 years ago

Switching Relationship for model based on field

Posted 3 years ago by cullymason

So I have a Model: Comment, that belongs to a "user". The reason the user is in quotes is because depending on the user_type field on the Comment model, the relationship changes to a different model. Here is the code that I have to make that work in the Comment model

public function user()
            return $this->belongsTo('App\User');
            return $this->belongsTo('App\Contact');

However, when I go to get the user via Comment::find(1)->user, it only works if the user_type is user. In other words, if the user type is contact then the relationship always returns null.

Is it possible to switch the relationship like this? What other information would you need from me to make this more clear?

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