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_idreferences the columnidon auserstable. - Add the
ON DELETE CASCADEreferential action so that deleting the user with the id ofuser_idwill delete the current record too.
Sources
Tagged:
Laravel
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment