How many types do you have? A switch statement might work well.
class Project extends Model {
public function type()
{
switch ($this->$type)
{
case 'wordpress':
return $this->hasOne('App\WordpressProject');
case 'anotherType':
return $this->hasOne('App\AnotherTypeOfProject');
}
}
}
It seems basically the same logic. So it is not a bad way to do it? Making relationships conditional by putting if statement around Eloquent relationship.
I couldn't comment if there is logically a better solution. It certainly is not a bad one. I assumed that you wanted a way to express the possibility of having many relationships that's all.
There seems to be a new related video on Laracast about this problem although the video does not cover the situation when there are different fields/columns needed depending on the type (e.g. user of type admin may have more data than regular users).
Check out the polymorphic relations documentation. This might be what you need.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community