Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stephan-v's avatar

Using Polymorphism

Hello,

I'm busy making a small app with laravel that contains 3 tables. Users, contests, submission. A submission can belong to a user but also a contest. It seems that polymorphism is a good fit for this so I watched the "Polymorphic huh?" episode.

It seems to click with me but I have not yet seen an example where(in this example) a single submission belongs to both a user and contest at once. Most examples of polymorphism in laravel seem to display as either belonging to one model or the other. This makes sense since the _type attribute can only hold a single value.

How do I implement this, making two rows seems to be a hassle. Maybe I just don't understand it well enough?

0 likes
1 reply
JarekTkaczyk's avatar

@stephan-v Then you use many-to-many polymorphic relation with pivot table:

// assuming submissables is the pivot table and submissable_type .._id are the fields
// Submission model
public function users()
{
  return $this->morphedByMany(User::class, 'submissable');
}
public function contests()
{
  return $this->morphedByMany(Contest::class, 'submissable');
}

// User / Contest models
public function submissions()
{
  return $this->morphedToMany(Submission::class, 'submissable');
}
1 like

Please or to participate in this conversation.