How to add foreign key in Laravel migration?

Member

by aubrey , in category: PHP Frameworks , 9 months ago

How to add foreign key in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 3 months ago

@aubrey 

To add a foreign key constraint to a column in a Laravel migration, you can use the foreign method of the Blueprint class within the up method of your migration file.


Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class AddForeignKeyToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreign('country_id')
                ->references('id')->on('countries')
                ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropForeign('users_country_id_foreign');
        });
    }
}


This example adds a foreign key constraint to the country_id column of the users table that references the id column of the countries table. The onDelete method specifies the action to be taken when a record in the countries table is deleted. In this case, the action is cascade, which means that any records in the users table that reference the deleted record will also be deleted.


You can then run the migration using the php artisan migrate command.