Categories
Fixing Stuff Laravel Samuel

Update Laravel Column To Allow NULLABLE Entries

We had a client request today that 2 fields on their user creation page be updated to allow for NULL entries. Once we updated the site to Laravel 5.6 the new stricter settings were throwing errors with these blank input fields. Luckily in our case both columns did not have any data in them, so this made our change relatively straightforward. Jumping into it we first created new migrations for both columns:

//Update column to allow null entries

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('historical_overtime', 32)->nullable()->after('shift_code');;

        });
    }

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

From Here we pulled up phpMyAdmin and dropped our old columns using the code:

ALTER TABLE users DROP COLUMN middle_name;
ALTER TABLE users DROP COLUMN historical_overtime;

We then deployed our new migration files to our the live server, ran them to install the new DB columns and away goes our error. For future reference the error code we fixed with this is:

SQLSTATE[2300]: Integrity constraint violation: 1048 Column 'middle_name' cannot be null

If the DB columns would have had information in them, instead of deleting them we could have updated them using the code below:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // change() tells the Schema builder that we are altering a table
        $table->integer('middle_name')->unsigned()->nullable()->change();
    });
}