Shorthand for creating polymorphic columns in Laravel

For creating polymorphic relationship columns, we need to define morphable_id, morphable_type
An example :
taggable_id, taggable_type

In our migration, we can define the columns in this way :

$table->unsignedBigInteger('taggable_id');
$table->string('taggable_type');
$table->index(['taggable_id', 'taggable_type']);

Did you know we have shorthand command alias (methods) for doing the same things:

$table->morphs('taggable');

The above 3 lines of codes and this one line code is equivalent to each other. Both will create taggable_id and taggable_type columns for us and create a compound or composite index as well.

And we have shorthand command alias for dropping the columns as well :

$table->morphs('taggable');

This will drop the taggable_id and taggable_type columns for us.

Hope this tips was helpful for you 🙂 Happy coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest