Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting default value in laravel migration issue

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
        });
    }
}
 

>Solution :

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');
                        
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading