DEV Community

Cover image for Laravel And Polymorphism(DB Example)
Mohammad ALi Abd Alwahed
Mohammad ALi Abd Alwahed

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?

php

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!

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

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 (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay