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

Image for post
Image for post

First read . 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:

commentable_id , commentable_type

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

1- The common way:

$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


Which adds morphable_id UNSIGNED BIGINT and morphable_type VARCHAR equivalent columns.

Note: to drop morphs columns we can do:


Which drop the morphable_id and morphable_type columns.

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store