How to create foreign key in laravel migration?

by lindsey.homenick , in category: PHP CMS , 7 months ago

How to create foreign key in laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 7 months ago

@lindsey.homenick 

To create a foreign key in a Laravel migration, you can use the foreign method provided by Laravel's Schema builder. Here's an example of how to create a foreign key in a Laravel migration:

1
2
3
4
Schema::table('child_table', function (Blueprint $table) {
    $table->unsignedBigInteger('parent_id');
    $table->foreign('parent_id')->references('id')->on('parent_table')->onDelete('cascade');
});


In the above code snippet, we are creating a foreign key parent_id in the child_table that references the id column in the parent_table. We are also specifying that if a parent record is deleted, all child records associated with that parent should also be deleted (onDelete('cascade')).


Remember to replace child_table and parent_table with the names of your actual database tables.