Search code examples
laraveleloquentpolymorphic-associations

Laravel 5 Polymorphic Relationship


Not entirely clear on this yet as it would be the first time I'm tinkering with this. My table structure is as follows:

questions
- id
- type_id

multiple_choice_options
- id
- question_id

drag_and_drop_options
- id
- question_id

The type_id field on the questions table determines which options table to load from. So essentially I'd like to setup a relationship on the Question model as follows:

class Question extends Model {
    public function options() {
        // not sure what to return here?
    }
}

And for the option models would this be the correct inverse definition?

class MultipleChoiceOption extends Model {
    public function question() {
        return $this->belongsTo(Question::class);
    }
}

class DragAndDropOptions extends Model {
    public function question() {
        return $this->belongsTo(Question::class);
    }
}

How do I set this up to work with polymorphic relationships?


Solution

  • You could simply build a switch in the options() relation:

    class Question extends Model {
        public function options() {
            if ($type_id === 'multiple') {
                return $this->hasMany(MultipleChoiceOption::class);
            } else {
                return $this->hasMany(DragAndDropOptions::class);
            }
        }
    }
    

    Careful though with these magic relations, you'll need additional type checks and careful coding in your app.