Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Experienced Software Engineer specializing in the recruitment field, with a robust background in software engineering and SAAS products. Proficient in utilizing Laravel for backend development
  • Location
    Amman , Jordan
  • Education
    UOP
  • Work
    Software Engineer
  • Joined

More fromMohammad ALi Abd Alwahed

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp