0
0
LaravelHow-ToBeginner · 3 min read

How to Add Column Using Migration in Laravel

To add a column using a migration in Laravel, create a new migration file with php artisan make:migration, then use Schema::table in the up method to add the column with methods like $table->string('column_name'). Run php artisan migrate to apply the changes.
📐

Syntax

Use Schema::table('table_name', function (Blueprint $table) { ... }); inside the up method of your migration. Inside the closure, call the column type method like $table->string('new_column'); to add a new column.

The down method should reverse the change, usually by dropping the column with $table->dropColumn('new_column');.

php
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('nickname');
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('nickname');
    });
}
💻

Example

This example adds a nickname column of type string to the users table. The up method adds the column, and the down method removes it to allow rollback.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddNicknameToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('nickname')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('nickname');
        });
    }
}
Output
Migration runs successfully, adding 'nickname' column to 'users' table.
⚠️

Common Pitfalls

  • Forgetting to run php artisan migrate after creating the migration.
  • Not adding the down method or incorrectly dropping the column, which breaks rollback.
  • Trying to add a column that already exists causes errors.
  • Not using Schema::table for modifying existing tables (using Schema::create instead is wrong).
php
<?php
// Wrong: Using Schema::create to add column
Schema::create('users', function (Blueprint $table) {
    $table->string('nickname');
});

// Right: Use Schema::table to add column
Schema::table('users', function (Blueprint $table) {
    $table->string('nickname');
});
📊

Quick Reference

ActionCode Example
Create migrationphp artisan make:migration add_nickname_to_users_table --table=users
Add column in up()$table->string('nickname')->nullable();
Remove column in down()$table->dropColumn('nickname');
Run migrationphp artisan migrate
Rollback migrationphp artisan migrate:rollback

Key Takeaways

Use Schema::table inside the migration's up() method to add columns to existing tables.
Always define the down() method to drop the added column for safe rollbacks.
Run php artisan migrate to apply your migration changes.
Avoid using Schema::create when modifying existing tables.
Check for existing columns to prevent migration errors.