DEV Community

Cover image for Understanding Polymorphism vs. Polymorphic in Programming
Muhamad Sulaiman
Muhamad Sulaiman

Posted on

1 1 1

Understanding Polymorphism vs. Polymorphic in Programming

Introduction

If you've ever dived into Object-Oriented Programming (OOP) or worked with an ORM like Laravel's Eloquent, you've likely come across the terms Polymorphism and Polymorphic Relationship (will use Polymorphic after this). While they sound similar, they refer to two distinct concepts.

Many developers, especially those new to these concepts, often confuse them. In this post, I'll break down what each term means, how they are used, and why understanding the difference is crucial for writing clean and efficient code.


What is Polymorphism?

Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to be used with different underlying data types, improving code reusability and flexibility.

There are two primary types of polymorphism. Method Overriding and Method Overloading. For the sake of the PHP and this sharing, we focus on the first type only.


Example of Polymorphism in PHP (Method Overriding)

Let's take a real-world example. Assume we have a User system where different types of users (Admin, Customer) have different access levels.

/**
* Main (or Parents) Class
*/
class User {
    public function getRole() {
        return "General User";
    }
}

/**
* Child Class
*/
class Admin extends User {
    public function getRole() {
        return "Administrator - Full Access";
    }
}

/**
* Child Class
*/
class Customer extends User {
    public function getRole() {
        return "Customer - Limited Access";
    }
}

/**
* Instantiate the Class - Object
*/
$users = [new Admin(), new Customer(), new User()];

foreach ($users as $user) {
    echo $user->getRole() . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

Output

Administrator - Full Access
Customer - Limited Access
General User
Enter fullscreen mode Exit fullscreen mode

Here, even though we are calling getRole() on different objects, they return different results based on their respective class implementations. This is the power of polymorphism.

Ok now, I hope you understand about polymorphism. Let's go to other terms, polymorphic.


What is a Polymorphic?

A Polymorphic is a database design pattern used in Object-Relational Mapping (ORM) systems like Laravel's Eloquent. It allows a single model to be associated with multiple other models without needing multiple foreign keys.

For example, let's say we have an Image model that can be associated with both a Post and a User.

Instead of creating separate post_id and user_id columns in the images table, we use a polymorphic relationship with imageable_id and imageable_type columns.

Example of Polymorphic Relationship in Laravel

In your migration file :

Schema::create('images', function (Blueprint $table) {
    $table->id();
    $table->string('url');
    $table->morphs('imageable');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

In your Model :

/**
* Image Class
*/
class Image extends Model {
    public function imageable() {
        return $this->morphTo();
    }
}

/**
* Post Class
*/
class Post extends Model {
    public function images() {
        return $this->morphMany(Image::class, 'imageable');
    }
}

/**
* User Class
*/
class User extends Model {
    public function images() {
        return $this->morphMany(Image::class, 'imageable');
    }
}
Enter fullscreen mode Exit fullscreen mode

With this codes, you can do like this when Data Creation :

$post = Post::find(1);
$post->images()->create(['url' => 'post_image.jpg']);

$user = User::find(1);
$user->images()->create(['url' => 'profile_picture.jpg']);
Enter fullscreen mode Exit fullscreen mode

Now, both Post and User models can have associated images without needing separate foreign keys.


Polymorphic Relationships Exist Beyond Laravel

Although Laravel has made Polymorphic relationships popular in the PHP ecosystem, this concept exists in other frameworks and ORMs such as:

  • Django (Python) – Uses Generic Foreign Key

  • Hibernate (Java) – Uses Single Table Inheritance or Join Table Inheritance


Conclusion

Both Polymorphism and Polymorphic are crucial concepts, but they serve different purposes:

  • Polymorphism is an OOP concept that allows multiple classes to share the same interface and behave differently based on their implementation.

  • Polymorphic usually referred as Polymorphic Relationship are a database ORM feature that allows a single model to relate to multiple other models dynamically.


To visualize the difference

  • Polymorphism is like having different types of users (Admin, Customer, Guest) who inherit from a common User class but override methods to behave differently.

  • Polymorphic are like an Image table where a single image can belong to either a Post, a User, or even a Product, without needing multiple foreign keys.


Understanding the difference between these two concepts helps you write cleaner, more maintainable, and scalable code. Whether you’re designing an object-oriented system or a database schema, knowing when and how to use polymorphism can make a huge difference in your project's architecture.

Even there's some Cons. But I don't want to explain it here. Now, it's your job to find the Cons ;)

I'm sure you have implemented the polymorphism in your Laravel project. But Have you used polymorphic relationships in your projects? Let me know in the comments below! 🚀

API Trace View

Struggling with slow API calls? 👀

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (3)

Collapse
 
xwero profile image
david duymelinck

You make it overly difficult comparing polymorphism with polymorphic relationships. When you short the latter to polymorphic it makes no sense because you just removed a big part of the what determines the concept. It like saying lets shorten object-oriented programming to object programming.

Polymorphic relationships are a way to reduce pivot tables in a database. I never understood why it is a problem to have pivot tables if you use a tables based database.
If you want to avoid pivot tables use a graph database, there you can connect the nodes with as much relations as you want.
So polymorphic relationships are just a solution invented by people who never looked further than the tables based database (also called relational model, but this could cause confusion in this context).

Collapse
 
msulaimanmisri profile image
Muhamad Sulaiman

Thank you for the comment @xwero . I think there’s a misunderstanding here.

First. I explicitly mentioned at the beginning: "Polymorphic Relationship (will use Polymorphic after this)." So, within this article, "Polymorphic" refers specifically to Polymorphic Relationships in Laravel. It’s clearly stated, so there shouldn’t be any confusion.

Second. This post is not about comparing polymorphism and polymorphic relationships as if they are competing ideas. Instead, it's about highlighting their differences, since many developers mix them up.

Polymorphism is an OOP concept, while Polymorphic Relationships relate to database structure. Two different things with different purposes.

Third. Polymorphic relationships are not a way to "reduce pivot tables." Their purpose is to allow a single model to relate to multiple models dynamically. Pivot tables are used for many-to-many relationships, which is a different use case.

Saying that polymorphic relationships exist because people "never looked beyond relational databases" is misleading. They are a practical solution within relational databases to handle flexible relationships efficiently.

I appreciate the discussion, but I’d encourage you to reread the article carefully—the distinctions are clearly explained. Let’s focus on understanding the concepts rather than debating terminology. 😊

Collapse
 
xwero profile image
david duymelinck • Edited

The title of your post is; Understanding Polymorphism vs. Polymorphic in Programming. That is why I clicked on it, because I didn't know what the meaning of polymorphic was.
Why would you shorten the term in the first place, is it that hard to write polymorphic relationship every time?
If it is not a comparison why have the polymorphism content in the post? Just because they sound similar? That could be one line in the post. But you mention it in the title, and in the conclusion.
You even blend them in this sentence:

Whether you’re designing an object-oriented system or a database schema, knowing when and how to use polymorphism can make a huge difference in your project's architecture.

If you don't use polymorphic relationships, how would you create your database schema for a one to many relationship? Pivot tables with the names of the two models and their ids as columns, no?
You even mention it in the post:

It allows a single model to be associated with multiple other models without needing multiple foreign keys.

What is the purpose of the multiple foreign keys?

If you normalise a relational database schema and you can't use foreign keys, you know it will lead to performance issues once the dataset becomes larger.
The id field of the polymorphic relationship can not be used as a foreign key, because it stands for multiple tables based on the type field.
Because the type field value can be any string, the data in that field can become inconsistent, or relationships can become invalid.
If you had a relational database normalisation exam, you will fail with a polymorphic relationship.
And you call it practical and scalable?

What is the meaning of a flexible relationship? A database has to be correct because it is a source of truth. In an ecommerce application I don't want a flexible relationship between a customer and their orders and payments.

One thing the nosql hype of a few years ago did well was bringing other database models to the surface; value-key model, column model, document model, graph model.
Now we have databases that support multiple models, so we can create the fastest and cleanest schemas for specific purposes.
Not everything has to be in a relational model because that is default model of the ORM.
That is where my "never looked beyond relation databases" comment comes from.

I hope that clears up my comment for you?

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →