475

I can't figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...

<?php

public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate.

How do I add new columns?

ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
kim larsen
  • 5,111
  • 6
  • 19
  • 17
  • It would be useful if you could include any errors you're getting; what do you expect to happen; and what actually happens? – Phill Sparks May 28 '13 at 12:24
  • 23
    Great question. There is a lot of migration documentation out there, and it shows you the API and how to create tables the FIRST TIME. Then it all fails as you develop your app more and need to modify your db structure. – Andrew Koper Nov 11 '16 at 17:25
  • You must use php artisan make:migration – AlirezaAhmadi Apr 21 '22 at 17:22

20 Answers20

1068

To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

for Laravel 3:

php artisan migrate:make add_paid_to_users

You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

and don't forget to add the rollback option:

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

Then you can run your migrations:

php artisan migrate

This is all well covered in the documentation for both Laravel 4 / Laravel 5:

And for Laravel 3:

Edit:

use $table->integer('paid')->after('whichever_column'); to add this field after specific column. applicable for MySQL only

Phill Sparks
  • 20,000
  • 3
  • 33
  • 46
  • 6
    Just `php artisan migrate` – Phill Sparks May 28 '13 at 12:30
  • Something is wrong. I make "db:make" to make a new migration file. And then i put the Schema::table('users', function($table) { $table->integer('paid'); }); into it. And run "php artisan migrate", but getting Fatal error: Cannot redeclare class Users in /Applications/XAMPP/xamppfiles/htdocs/adsense/application/migrations/2013_05_28_122527_users.php on line 3 – kim larsen May 28 '13 at 12:43
  • 1
    Creating migrations is also covered in the documentation. You should give it a more specific name, like "add_paid_to_users", this way it will not clash with your model clash. – Phill Sparks May 28 '13 at 12:55
  • Seems like any Laravel 3 doc URL is redirecting to the Laravel 4 docs. Here are the links to the 3 doc for [schema builder](http://three.laravel.com/docs/database/schema#adding-columns) and [migrations](http://three.laravel.com/docs/database/migrations) –  Aug 18 '14 at 17:21
  • Hi @tubes, I'll fix the links. The Laravel 3 docs are now hosted at http://three.laravel.com/docs – Phill Sparks Aug 19 '14 at 08:00
  • For completeness, the `function down()` can also be implemented to allow reversing the migration: `public function up() { Schema::table('users', function($table) { $table->integer('paid'); }); } public function down() { Schema::table('users', function($table) { $table->dropColumn('paid'); }); }` As per docs: [Dropping Columns](http://laravel.com/docs/4.2/schema#dropping-columns) – ATutorMe Jan 14 '15 at 00:34
  • 8
    As of Laravel 5, this command would now be `php artisan make:migration add_paid_to_users` – mikelovelyuk Apr 09 '15 at 11:29
  • @mike3875 it's probably worth adding that as an answer of your own if you think it would be useful. It'll be lost here in the comments and isn't really something I want to confuse my answer with (which is about Laravel 3/4) – Phill Sparks Apr 09 '15 at 11:34
  • Lol, by default it is Schema::create('table_name' .. took me a while to figure out it was supposed to be Schema::table( – P_95 Dec 04 '15 at 12:35
  • lacking Blueprint in $table, so this would be function(Blueprint $table) – Juni Brosas Feb 12 '16 at 11:02
  • @JuniBrosas for Laravel 5.2 you'd be correct, this question was asked of Laravel 3... things have changed a bit since then! – Phill Sparks Feb 12 '16 at 11:04
  • Is there anyway I can add column in my existing table using migration without losing my data? Please help. Thanks – Eli Apr 19 '16 at 12:32
  • @Eli that's exactly what this should do. – Phill Sparks Apr 21 '16 at 11:07
  • To be more precise, do not forget to add the `Blueprint` type to the `up` and `down` function arguments (like `function(Blueprint $table)`). – Alex Nov 10 '17 at 19:33
  • I can't understand the meaning of "and don't forget to add the rollback option:" Where i can put rollback option? Please reply me as soon as possible!!! – Yagnesh bhalala Dec 21 '17 at 13:23
  • @Yagneshbhalala the rollback is the "down" function - how to undo the up function. – Phill Sparks Dec 23 '17 at 22:29
  • @Phill Sparks using this command `php artisan make:migration rollback` – Yagnesh bhalala Dec 25 '17 at 12:23
  • `$table->integer('paid')->after(whichever_column);` this only supports mysql? – Mohammad Shoriful Islam Ronju May 29 '18 at 09:57
  • This would be php artisan make:migration and not php artisan migrate:make – Luiz Wynne May 22 '19 at 13:11
  • 1
    It is a good idea to do #php artisan migrate --pretend before #php artisan migrate just to check what is the migration will do before the migration is processed, – Amir Khalil May 07 '20 at 20:31
  • I couldn't find that exact same example in the docs. Still works in Laravel 9 though – Pathros Jun 17 '22 at 16:50
82

I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.

To make things quicker, you can use the flag "--table" like this:

php artisan make:migration add_paid_to_users --table="users"

This will add the up and down method content automatically:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}

Similarily, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!

camelCase
  • 5,460
  • 3
  • 34
  • 37
  • 2
    That was not the case in Laravel 5.0, `Blueprint` was added in Laravel 5.1. Just a point of clarification is all. – Phill Sparks Feb 12 '16 at 11:07
  • @PhillSparks You're right, thank you for catching my mistake. I've updated to clarify the version in which this can be used. – camelCase Feb 12 '16 at 14:39
82

In case you want to add new column as a FOREIGN KEY to an existing table.

Create a new migration by executing this command : make:migration

Example :

php artisan make:migration add_store_id_to_users_table --table=users

In database/migrations folder you have new migration file, something like :

2018_08_08_093431_add_store_id_to_users_table.php (see the comments)

<?php

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

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            
            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');
            
            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            
            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

After that run the command :

php artisan migrate

In case you want to undo the last migration for any reason, run this command :

php artisan migrate:rollback

You can find more information about migrations in the docs

chebaby
  • 7,362
  • 50
  • 46
  • 1
    The rollback wont work like this. For rollback to work, ```$table->dropForeign('posts_store_id_foreign'); $table->dropColumn('store_id');``` – Akshay K Nair Apr 30 '21 at 17:14
30

If you're using Laravel 5, the command would be;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.

php artisan migrate is still the same though.

mikelovelyuk
  • 4,042
  • 9
  • 49
  • 95
24

In Laravel 8

php artisan make:migration add_columnname_to_tablename_table --table=tablename

then after creating migration in

public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            $table->datatype('column_name')->nullable();
        });
    }
public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            $table->dropColumn('column_name');
        });
    }

then run

php artisan migrate

if you face error then rename the migration name with the date before the table created and then run again php artisan migrate

Sfili_81
  • 2,377
  • 8
  • 27
  • 36
Shaarif Mehmood
  • 271
  • 2
  • 4
20

You can add new columns within the initial Schema::create method like this:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.

tplaner
  • 8,363
  • 3
  • 31
  • 47
  • Something is wrong. I make "db:make" to make a new migration file. And then i put the Schema::table('users', function($table) { $table->integer('paid'); }); into it. And run "php artisan migrate", but getting Fatal error: Cannot redeclare class Users in /Applications/XAMPP/xamppfiles/htdocs/adsense/application/migrations/2013_05_28_122527_users.php on line 3 – kim larsen May 28 '13 at 12:42
  • You should name each of the migrations something unique when creating them. Typically the initial create I'll name `create_users_table`, then if I'm adding columns: `add_email_password_columns_to_users`. – tplaner May 28 '13 at 12:46
  • yeah as evolve says, surely its better to stick with original laravel design philosophies and only use the "`add_`" verb at front of each file to keep track of changes. this way its easier to track changes for version control etc because a new add file is created for every iteration. If you just went and kept modifying the "`create_`" it would be hard to know that x employee, had messed something up by removing an index, or adding a new column etc etc. at least that makes sense in my head! :) – wired00 Jan 22 '15 at 03:02
14

Laravel 7

  1. Create a migration file using cli command:

    php artisan make:migration add_paid_to_users_table --table=users

  2. A file will be created in the migrations folder, open it in an editor.

  3. Add to the function up():

Schema::table('users', function (Blueprint $table) {
    // Create new column
    // You probably want to make the new column nullable
    $table->integer('paid')->nullable()->after('status');
}
  1. Add to the function down(), this will run in case migration fails for some reasons:

    $table->dropColumn('paid');

  2. Run migration using cli command:

    php artisan migrate


In case you want to add a column to the table to create a foreign key constraint:

In step 3 of the above process, you'll use the following code:

$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');

$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');

In step 4 of the above process, you'll use the following code:

// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');
Rehan Arshad
  • 350
  • 3
  • 13
  • I am very new to Laravel. It is supposed to make things easier and I can see that. However, why would I do all of the above if I want to add a column to my table? Why would I not just add it to the sql table directly via phpmyadmin or the mysql CLI? Again I am new. It appears that there will be a lot of one-time code created if I am interpreting these answers correctly. – MichaelB Jan 21 '21 at 14:24
  • 1
    @MichaelB Well, Laravel recommends to use Migrations to add new tables or fields to current tables or create relations. Why? Because at the time moving to 'Production Environment' (Live website) from 'Development Environment', you don't have to create all those tables and relations in database by your own. You just need to upload the files to server, update .env file and run the migration command. Laravel will create the tables with relations for you. – Rehan Arshad Jan 22 '21 at 23:09
  • Thank you Rehan Arshad, this command still works on Laravel 10. In my case I directly use the command on terminal. $ php artisan make:migration add_paid_to_users_table – Two Jun 21 '23 at 07:15
11

this things is worked on laravel 5.1.

first, on your terminal execute this code

php artisan make:migration add_paid_to_users --table=users

after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

after that go back to your terminal and execute this command

php artisan migrate

hope this help.

Rosidin Bima
  • 227
  • 3
  • 5
7

First rollback your previous migration

php artisan migrate:rollback

After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file

php artisan migrate
noobgrammer
  • 71
  • 1
  • 3
7

STEP 1

php artisan make:migration add_sex_to_users_table --table=users

STEP 2

In the newly generated migration file, you will find up and down hook methods. in up hook, add there columns that you want to add, and in down hook, add there columns that you need to remove. for example, Me i need to add sex on column of users, so I will add there following line in the up hook.

$table->integer('quantity')->default(1)->nullable();

So I have something like this

public function up()
{
    Schema::table('service_subscriptions', function (Blueprint $table) {
        $table->integer('quantity')->default(1)->nullable();
    });
}

STEP 3

Run the migration command as follows

php artisan migrate

Then you will have a new column added

Adriaan
  • 17,741
  • 7
  • 42
  • 75
MUHINDO
  • 788
  • 6
  • 10
5

WARNING: this is a destructive action. If you use this ensure you back up your database first.

You can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :

$ php artisan migrate:refresh
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mahana Delacour
  • 179
  • 1
  • 1
  • 21
    Refresh will empty the table – JohnTaa Oct 02 '17 at 03:11
  • 11
    This is incredibly dangerous - if some people have the run the old version, some will have the new, and chaos will ensue. In Liquibase, if you edit a file, it will fail unless you explicitly put in exceptions to allow it, and you can only do this in very few cases. E.g. if you make a column not-null when some database already have null data in them, it will break. – John Little Oct 04 '17 at 21:41
  • 5
    It would be better, if you edit your answer and mention that it would empty your table, it would be better. – Abel Sep 12 '18 at 09:06
  • 1
    **Note:** This command will **clean entire databases tables**, if you want to use it, then backup your database first – Udhav Sarvaiya Apr 12 '19 at 05:55
4

Add column to your migration file and run this command.

php artisan migrate:refresh --path=/database/migrations/your_file_name.php
Hamza Khan
  • 341
  • 2
  • 3
2

In laravel 8

php artisan make:migration add_paid_to_users_table --table=users

public function up()
 {
    Schema::table('users', function($table) {

        $table->integer('paid');

  });

}

In laravel 9

add a new column in existing table

php artisan make:migration add_paid_to_users_table

if you want to create new migration then do the below code

php artisan make:migration create_users_table --create=users
vimuth
  • 5,064
  • 33
  • 79
  • 116
0

First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command for Laravel 4:

php artisan migrate:make add_paid_to_users

And for laravel 5 version

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

Then you need to use the Schema::table() . And you have to add the column:

public function up()

{

    Schema::table('users', function($table) {

        $table->integer('paid');

    });

}
miken32
  • 42,008
  • 16
  • 111
  • 154
hammad khan
  • 57
  • 3
  • 6
0

From solution of mikelovelyuk, I removed the --table

Using Laravel 10

php artisan make:migration add_paid_to_users

Inside the Migration file For instance 2023_06_21_071221_add_paid_to_users_table

public function up(): void
{
    Schema::table('users', function (Blueprint $table) {
       $table->string('paid')->nullable();
    });
}

/**
* Reverse the migrations.
*/
public function down(): void
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('paid');
    });
}

Then migrate

php artisan migrate
Two
  • 512
  • 4
  • 17
-1

If you don't want to split the blueprint(schema) into two migration file then the best thing you can do is drop the table from the database and then rename the migration file's last number and do

php artisan migrate

This helps you to protect the data of other tables.

Wisdomrider
  • 170
  • 7
-1

Run this command: php artisan migrate:fresh --seed it will drop the table and re add it updating all the columns adding to the database

-1

What you can do is Like,

Schema::create('users', function ($table) { $table->integer("paid"); });

After Writing this write command php artisan migrate or php artisan refresh What i personally prefer is to refresh rather than fresh migration because if you do fresh migrate it will remove all the data refresh will not.

but only exception is if you do refresh and if you have any foreign key in table so it will not going to re-establish the relationship so you will get error like,

Cannot add foreign key constrain

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 21 '21 at 16:32
-1

If none of the solve worked, you might have recreated the migration file then added a new column and tried to run php artisan migrate to update the old table which will try to create that table but the table already exists so it gives an error. To solve that rename the migration file as previously named (started with a date), then add new column run php artisan migrate that will actually update the old one instead of create, solved my problem.

Sazzad
  • 176
  • 1
  • 9
-2

Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.

$ php artisan tinker

Here's an example one-liner for the terminal:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })



(Here it is formatted for readability)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});
mfink
  • 1,309
  • 23
  • 32