Hello developers! In this article, we'll see laravel 10 drop foreign keys using migration. Here, we'll drop foreign key constraints using migration in laravel 10. To drop a foreign key, you can use the dropForeign
method, passing the name of the foreign key constraint to be deleted as an argument.
Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix.
$table->dropForeign('posts_user_id_foreign');
Alternatively, you can pass an array containing the column name that holds the foreign key to the dropForeign
method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions.
$table->dropForeign(['user_id']);
Example:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('profile_picture');
$table->string('password', 60);
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
Drop Column Migration:
Schema::table('users', function (Blueprint $table) {
$table->dropForeign('users_post_id_foreign');
$table->dropColumn('post_id');
});
You can enable or disable foreign key constraints within your migrations by using the following methods:
Schema::enableForeignKeyConstraints();
Schema::disableForeignKeyConstraints();
Schema::withoutForeignKeyConstraints(function () {
// Constraints disabled within this closure...
});
You might also like:
- Read Also: How to Create Multiple Database Connections in Laravel 10
- Read Also: Laravel 10 Remove Column from Table using Migration
- Read Also: Importing Excel File into Database Using Python
- Read Also: Laravel 10 With Vue JS CRUD Operation