How To Drop Foreign Key In Laravel 10 Migration

Websolutionstuff | Apr-28-2023 | Categories : Laravel

In this article, we will explore the process of removing foreign key constraints in Laravel 10 migrations. We will delve into the specific steps for dropping foreign keys in Laravel 10 using migration techniques. To accomplish this, we will utilize the dropForeign method, specifying the name of the foreign key constraint to be deleted as an argument.

It's essential to note that foreign key constraints follow the same naming convention as indexes. Therefore, removing them is not as straightforward as using dropColumn(). Instead, we need to first drop the foreign key constraint using dropForeign(), and then we can proceed to delete the column using dropColumn().

Let's learn how to drop foreign keys in Laravel 10 migrations, understand the methods for removing foreign key constraints, and effectively manage your database schema changes.

$table->dropForeign('posts_user_id_foreign');

Alternatively, you may 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 might also like:

Recommended Post
Featured Post
Laravel 10 Composer-runtime-api ^2.2 Error - Fixed
Laravel 10 Composer-runtime-ap...

In this article, we will see laravel/framework[v10.0.0, ..., v10.0.3] require composer-runtime-api ^2.2 error fixed...

Read More

Mar-07-2023

How To Create Custom Login Page In Django
How To Create Custom Login Pag...

In this article, we will see how to create a custom login page in django. how to allow user registration, login, an...

Read More

May-14-2022

How To Add Foreign Key In Laravel 10 Migration
How To Add Foreign Key In Lara...

In this article, we will see how to add a foreign key in laravel 10 migration. Here, we will learn about laravel 10...

Read More

May-05-2023

How to Manage Time Zones in React.js Applications
How to Manage Time Zones in Re...

In the interconnected world of web development, where applications are accessed by users spanning multiple time zones, t...

Read More

Sep-04-2023