0

my code below is working fine. Problem is when i got data in database which is null in user_id field. Migration rollback will not pass successfully. What is good approach to solve this problem? Should i change every null in column user_id to empty string before i change nullable to false in rollback?

    public function up()
    {
        Schema::table('classes', function (Blueprint $table) {
            $table->text('user_id')->nullable()->change();
        });
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('classes', function (Blueprint $table) {
            $table->text('user_id')->nullable(false)->change();
        });
    }

1 Answer 1

2

This problem has been seem before, I couldn't find other solution than update the values to empty string before changing the column, the database engine will always complaint.


Updated:

You could do this like this and should work:

use Illuminate\Support\Facades\DB;

/*
*
* Some code
*
*/


public function up()
{
    DB::table('classes')->whereNull('user_id')->update(['user_id'=>'']);
    Schema::table('classes', function (Blueprint $table) {
        $table->text('user_id')->nullable()->change();
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

okay, thank you so much for your answer. DB::statement(raw_sql) is good solution or maybe you have better for this situation?
Yes you could do that, just updated my answer.
thank you so much , your solution is better than just raw sql

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.