Home > Software engineering >  Setting default value in laravel migration issue
Setting default value in laravel migration issue

Time:04-07

In my laravel application, I have two tables called users, and stat_user.

In my stat_user table I need to add a new column called, added_by.

added_by is a foreign key.

default value of added_by, has to be id of user's table.

How can I write my migrattion file to full fill both my needs to add that extra columns.

This is what I have done so far... I'm struggling to add that default value...

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddAddedByToCertificateUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('stat_user', function (Blueprint $table) {
            $table->unsignedBigInteger('added_by')->after('user_id');
            $table->foreign('added_by')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('cstat_user', function (Blueprint $table) {
            $table->dropColumn('added_by');
        });
    }
}
 

CodePudding user response:

Okay, adding the new column with the relationship will cause an issue with the old records so we need first to make it nullable

  Schema::table('stat_user', function (Blueprint $table) {
            $table->unsignedBigInteger('added_by')->nullable()->after('user_id');
            $table->foreign('added_by')->references('id')->on('users');
        });

then we can run the following query to set the default value for the old records

\DB::statement('UPDATE stat_user SET added_by = user_id');

you can also combining them in the same migration file

public function up()
    {
        //
        Schema::table('stat_user', function (Blueprint $table) {
                $table->unsignedBigInteger('added_by')->nullable()->after('user_id');
                $table->foreign('added_by')->references('id')->on('users');
            });
        
        \DB::statement('UPDATE stat_user SET added_by = user_id');
                        
    }
  • Related