Polymorphic relationship

Posted 2 years ago by amcardwell

I know... another question on polymorphic relationships. I've looked at every other topic on this but I just cant wrap my head around it. Pleeeease guys, I need some help!

I have many different forms on my website (with different attributes) that get filled out and the data gets posted to its own model based on the form. So I have a Form model that lists all of the forms with a name attribute, and another model based on that form that lists each "submission". So, for example, if I had forms called ContactForm and RegistrationForm, my models would look like this:

// Form.php
- id
- name

// ContactFormsData.php
- id
- first_name
- last_name
- phone

// RegistrationFormData
- id
- name
- date_registered
- likes_candy

Im almost positive that this is a one-to-many polymorphic relation, but I cant for the life of me figure out how to setup my relationships in order to query the data based on the form. Another post I read suggested creating a pivot table to join a Form to its related Model, but no matter what I did, the result returned null whenever I made a query to that relation.

I added a Submissions table with the attributes form_id, submittable_id, and submittable_type. I set up the relationships as follows:

// Form.php
{
    $this->hasMany('App\Submission');
}

// Submission.php
public function form()
{
    $this->belongsTo('App\Form');
}

public function submittable()
{
    $this->morphTo();
}

// ContactFormsData.php
public function submissions()
{
    $this->morphMany('App\Submission', 'submittable');
}

// RegistrationsData.php
{
    $this->morphMany('App\Submission', 'submittable');
}

Once set up, every variation of this query returned null:

$form = Form::find(1);
$form->submissions

Please help!

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

Reply to

Use Markdown with GitHub-flavored code blocks.