DEV Community

Cover image for Laravel And Polymorphism(DB Example)
Muhammed ALi Abdulwahed
Muhammed ALi Abdulwahed

Posted on

Laravel And Polymorphism(DB Example)

Long article, but it will benefit you if you're interested in improving your database design skills.

Polymorphism is one of the most important topics in OOP.

So, what is the morph relation in Laravel?

But how can we apply this concept to our database design in our project?

Simply, as a simple example of polymorphism, you create a class called "Shape" that has a function named "draw."

And two classes:

"Circle" extends "Shape"

"Square" extends "Shape"

In both cases, we override the "draw" function.

$a = new Circle();

$b = new Square();

$a.draw(); // It will draw a circle.

$b.draw(); // It will draw a square.

Now, how can we apply this to our database design?

In Laravel, for example, if you look at the documentation, you will find a type of relationship called "morph."

Simply, in a simple example from Laravel, we have multiple tables that contain images. Instead of creating an "image" column in each table, we create a "morphs" table for images.

So, how does it work?


Schema::create('media', function (Blueprint $table) { $table->text('image'); $table->morphs('imageable'); });

The "imageable" column will create two columns in the database: "imageable_id" and "imageable_type." The first column stores the ID of the related model, and the second column stores the class name.

This is how the relationship looks in the models for the entities we want to associate with images:

public function media() { return $this->morphMany(Media::class, 'imageable'); }

And this is how we store it:

$media->imageable_id = $ModelObject->id; $media->imageable_type = get_class($ModelObject);

That's it!

Top comments (0)