Step 1: Require doctrine/dbal package
The first step is to require the doctrine/dbal package by using the composer package manager.
composer require doctrine/dbal
Step 2: Call Schema Facade to Update Columns
Now you need to call the Schema facade and update the columns definition. You can create a new migration for this or you can right away call this function from within the route body. The code to change the column to nullable is as "nullable()->change()".
->nullable()->change();
<?php Route::get('/update-column', function () { \Schema::table('posts', function (Blueprint $table) { $table->integer('user_id')->unsigned()->nullable()->change(); }); });
Optional: Revert Column To Be Not Nullable
To revert the column you can set it to not nullable by passing "false" boolean value to the "nullable()"method.
$table->integer('user_id')->unsigned()->nullable(false)->change();
Optional: Using Migration
Create the migration by using the migrate command below.
php artisan make:migration make_usre_id_nullable_on_posts_table --table=posts
<?php public function up() { Schema::table('posts', function (Blueprint $table) { $table->integer('user_id')->unsigned()->nullable()->change(); }); } public function down() { Schema::table('posts', function (Blueprint $table) { $table->integer('user_id')->unsigned()->nullable(false)->change(); }); }
Optional: Using RAW SQL
You can also use the raw SQL to set the column nullable and below is the code.
<?php // set the column to nullable \DB::statement('UPDATE `posts` SET `user_id` = 0 WHERE `user_id` IS NULL;'); // set the column to not nullable \DB::statement('ALTER TABLE `posts` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
Leave a reply