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?
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:
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.