Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add a new column to an existing table of Laravel in a migration?
Laravel migrations provide a convenient way to modify your database schema over time. The make:migration Artisan command enables you to add new columns to existing tables without affecting existing data.
Creating an Initial Table
First, let's create a basic table using the migration command. The syntax for creating a new table is ?
php artisan make:migration create_students_table
This generates a migration file in the database/migrations directory ?
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStudentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('students');
}
}
Run the migration to create the table ?
php artisan migrate
Adding a New Column to Existing Table
To add a new column to an existing table, create a new migration with the --table option ?
php artisan make:migration add_address_to_students --table="students"
This generates a new migration file specifically for modifying the existing table ?
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddAddressToStudents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('students', function (Blueprint $table) {
$table->text('address');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('students', function (Blueprint $table) {
$table->dropColumn('address');
});
}
}
Key Points
The migration contains two important methods:
- up() Defines the schema changes to apply
- down() Defines how to reverse the changes (rollback)
Execute the migration to add the new column ?
php artisan migrate
Note: Ensure your Laravel application is properly configured with database connection details before running migrations.
Conclusion
Laravel migrations provide a version-controlled way to modify database schemas. Use make:migration with the --table option to add columns to existing tables while maintaining the ability to rollback changes when needed.
