How to Add a New Column to an Existing Table in a Laravel Migration
In this lesson, we are going to see how to add a new column to an existing table in a Laravel migration, let's assume that we are working on an e-commerce website and we must store the user's phone in the database but we forgot to add the column in the user's migration.
Create new migration
First, we will create a new migration and we will specify that the table is users.
php artisan make:migration add_phone_column_to_users_table --table=users
Add the column in the migration
Next, we will add the phone column to the newly created migration.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
$table->string('phone');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
$table->dropColumn('phone');
});
}
};
Run the migration
Finally, we run the newly created migration.
php artisan migrate