Home Add new columns as foreign key to existing table in Laravel
Post
Cancel

Add new columns as foreign key to existing table in Laravel

For example, we have a table called customers and we want to add a new column called user_id as foreign key to the users table. Here is how to do it.

  1. Create a migration file
    1
    
    php artisan make:migration add_user_id_to_customers_table --table=customers
    
  2. Add the following code to the migration file
    1
    2
    3
    4
    5
    6
    7
    
    public function up()
    {
     Schema::table('customers', function (Blueprint $table) {
         $table->unsignedBigInteger('user_id')->before('created_at');
         $table->foreign('user_id')->references('id')->on('users')->onDelete('SET NULL')
     });
    }
    
    1
    2
    3
    4
    5
    6
    7
    
    public function down()
    {
     Schema::table('customers', function (Blueprint $table) {
         $table->dropForeign(['user_id']);
         $table->dropColumn('user_id');
     });
    }
    
  3. Run the migration
    1
    
    php artisan migrate
    
This post is licensed under CC BY 4.0 by the author.

Connecting to GitHub with SSH

Cronjob with Laravel Task Scheduling