How to update a column as foreign key on laravel?

Member

by ryleigh , in category: PHP Frameworks , 10 months ago

How to update a column as foreign key on laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 10 months ago

@ryleigh 

To update a column as a foreign key in Laravel, you can use the unsignedBigInteger method in your migration file. Here's an example:

  1. Create a new migration file:
1
php artisan make:migration add_foreign_key_to_table_name


  1. Open the newly created migration file and add the following code to update the column as a foreign key:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public function up()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->unsignedBigInteger('foreign_key_column')->nullable();

        $table->foreign('foreign_key_column')->references('id')->on('related_table_name');
    });
}

public function down()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->dropForeign(['foreign_key_column']);
        $table->dropColumn('foreign_key_column');
    });
}


  1. Replace table_name with the name of your table, foreign_key_column with the name of the column you want to update as a foreign key, and related_table_name with the name of the related table.
  2. Run the migration to apply the changes:
1
php artisan migrate


After running the migration, the specified column in your table will be updated as a foreign key referencing the related table.

Related Threads:

How to declare a foreign key in laravel?
How to rename foreign key in laravel?
How to set a foreign key to nullable in laravel?
How to get the value of foreign key in laravel?
How to add foreign key in Laravel migration?
How to create foreign key in laravel migration?