Define foreign key constraints in Laravel migration
21 March 2022 (Updated 21 March 2022)
$table->foreignId('user_id')
->constrained()
->cascadeOnDelete();
This will do three things:
- Create an unsigned bigint column named
user_id
. - Add a foreign key constraint so that
user_id
references the columnid
on ausers
table. - Add the
ON DELETE CASCADE
referential action so that deleting the user with the id ofuser_id
will delete the current record too.
Sources
Tagged:
Laravel
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment