Laravel prepare migration file for Polymorphic Relationships

Make morphs morphable_id morphable_type equivalent columns in one command, one to one, one to many relationships

Panjeh
2 min readAug 20, 2019

First read This Part (new version). Then follow me.

There are two ways to prepare a migration file for one-to-one and one-to-many Polymorphic Relationships.

In making “Laravel migration file” we need to define these general columns:

morphable_id , morphable_type

For example they could be (like those in the Laravel document):

commentable_id ,

commentable_type ,

or

imageable_id

imageable_type

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

To insert these column inside the definition of migration file we can do:

1- The common way:

$table->unsignedBigInteger('morphable_id');
$table->string('morphable_type');
$table->index(['morphable_id', 'morphable_type']);

In this way, you create your own morph columns which can be interpreted by Laravel, but with a big integer.

2- Shorthand

$table->morphs('morphable');

Which adds morphable_id UNSIGNED BIGINT and morphable_type VARCHAR equivalent columns.

Note: to drop morphs columns we can do:

$table->dropMorphs('morphable');

Which drop the morphable_id and morphable_type columns.

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet