In this article, we will see how to add column after column in the Laravel migration. At some level of project completion, you might need to add the new column into the database table then you can easily add that by creating new migration in Laravel.
But you want to add that column after the particular column for better understanding. So let’s see how to do it.
-
Responsive Movie Landing Page Website Design
-
Anime Website Design Using HTML CSS JavaScript
-
Online Cake Shop Website Design With Source Code
-
Hotel Booking Website Design HTML CSS and JAVASCRIPT
Laravel Migration Add Column After
Laravel provides the after() method which used to place a new column after another column.
Let’s create a new migration for users table and then we will add a new column into a newly created table for better understanding.
php artisan make:migration create_users_table
The above command will create a new migration in database/migrations directory. We have added the following code into the newly created migration.
id();
$table->uuid('uuid')->unique();
$table->text('title')->nullable();
$table->text('first_name');
$table->string('email')->unique();
$table->string('password')->nullable();
$table->text('gender')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Let’s now, we want to add the new 2 columns, middle_name after the first_name and the birth_date column after the password column. Let’s create a new migration to add these 2 columns.
php artisan make:migration update_users_table --table=users
text('middle_name')->nullable()->after('first_name');
$table->text('gender')->nullable()->after('password');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('middle_name');
$table->dropColumn('gender');
});
}
}
In the above example, we have added 2 new columns in the up() method which will be executed when we run the php artisan migrate command. While we are dropping both columns in the down() method which will be executed when we run the php artisan migrate:rollback command.
Add Multiple Columns After A Column In Migrations
Laravel 9 has introduced a new after method which allows you to add multiple new columns after an existing column at the same time:
$table->after('password', function ($table) {
$table->string('address_line1');
$table->string('address_line2');
$table->string('city');
});
Schema::table('customers', function ($table) {
$table->string('address_line1')->after('password');
$table->string('address_line2')->after('address_line1');
$table->string('city')->after('address_line2');
});
You can see the crystal clear difference of code clarity.