How to declare a foreign key in laravel?

by filiberto , in category: PHP Frameworks , 2 months ago

How to declare a foreign key in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 months ago

@filiberto 

In Laravel, you can declare a foreign key in a migration file using the foreign method.


First, create a new migration file using the php artisan make:migration command:

1
php artisan make:migration add_foreign_key_to_table_name


Inside the newly created migration file, use the foreign method to add a foreign key constraint to a column. For example, if you want to add a foreign key constraint to the user_id column in a posts table that references the id column in the users table, you can do the following:

1
2
3
4
Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users');
});


In this example, user_id is the column you want to set as the foreign key, users is the table that the foreign key references, and id is the column in the users table that the foreign key references.


After adding the foreign key constraint to the migration file, run the migration using the php artisan migrate command to apply the changes to your database.