Add Column in Existing Migration Laravel
Hello, how are you! In this tutorial, I will show how to add columns in existing laravel migration. So, let's start from the beginning and create a new laravel project.
GitHub Repo: add-column-to-existing-migration
composer create-project laravel/laravel project
Open this project folder in any code editor. I would recommend using PhpStorm
Create a new database in MySQL and add your DB credentials in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel # your database name
DB_USERNAME=root # your database username
DB_PASSWORD=password # your database password
Now, let's create a product migration, and after I will add another migration to add a column in the products table.
php artisan make:migration create_products_table
# Products Table 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::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->boolean('is_active')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
};
Now, create another migration to add another column
php artisan make:migration add_price_to_products_table
# Add Price To Products Table 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('products', function (Blueprint $table) {
$table->unsignedInteger('price')->after('is_active');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn(['price']);
});
}
};
Now, run the migration (migrate all the migrations into MySQL database)
php artisan migrate
I hope it helps :)