In this tutorial we will discuss how to add foreign key column in existing table by migration. laravel add foreign key constraint migration. laravel migration droping column with foreign key constraint.
Laravel add foreign key column to existing table
Let our database have a users table which primary key id have unsigend biginteger type and there also have a products table which not have any relation with users table. Now we want to add a relation between users and products add a foreign key in products table.
Migration command
php artisan make:migration add_user_id_in_products_table --table=products
This command create a new migration
Foreign key add migration
In code we create a user_id foreign key in up() method and in down() method first remove foreign key constraint after drop that column.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use App\Models\Product; class AddUserIdProductsTable extends Migration { public function up() { Schema::table('users', function($table) { $table->biginteger('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade'); }); } // rollback the migration public function down() { Schema::table('users', function($table) { $table->dropForeign('user_id'); $table->dropColumn('user_id'); }); } }