tanmay_das's avatar

Foreign key constraints on Polymorphic Relationship

https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations

In this official example of polymorphic relations, the following table structure has been used:

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

How do I set commentable_id as a foreign key in such a way, so that when a post or a video is deleted, all comments associated with it will also be deleted?

The example shown here : https://laravel.com/docs/5.5/migrations#foreign-key-constraints

$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

makes use of the on() method by passing a single table name, users. What if I wanted to apply this on two tables, posts and videos?

0 likes
3 replies
Tayan's avatar

In Laravel 8, you can use the morphs() method on the table.

From the docs:

This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship. In the following example, taggable_id and taggable_type columns would be created:

$table->morphs('taggable');
1 like
clarkewingh's avatar

Just a quick note that the $table->morphs('taggable') method is essentially just an alias for $table->string('taggable_type'); $table->unsignedInteger('taggable_id').

It does not create any foreign key constraints. To the best of my knowledge, these don't work with polymorphic relationships.

Please or to participate in this conversation.