How to create a migration in Laravel 5 that only adds a column to an existing table

7.7k views Asked by At

I'm trying to add a number of new column to the generic 'users' table that comes with the Laravel 5 installation.

However I create a new migration that does a Schema::create as follows:

Schema::create('users', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('username');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->string('avatar');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('nickname');
    $table->rememberToken();
    $table->timestamps();
});

In the above I added the avatar, first_name, last_name and nickname columns.

My problem is that when I run php artisan migrate it's telling me Nothing to migrate.

How do I create an "update" migration?

3

There are 3 answers

2
Pwner On BEST ANSWER

From http://laravel.com/docs/5.1/migrations#creating-columns

Creating Columns

To update an existing table, we will use the table method on the Schema facade. Like the create method, the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance we can use to add columns to the table:

Schema::table('users', function ($table) {
    $table->string('email');
});

Also look at this from http://laravel.com/docs/5.1/migrations#creating-columns

Rollback / Migrate In Single Command Note: you will loose any data in the DB with this method

The migrate:refresh command will first roll back all of your database migrations, and then run the migrate command. This command effectively re-creates your entire database:

php artisan migrate:refresh
0
user3449007 On

You could also delete the migration row from the migrations table for a particular migration (the users migration usually with a batch of 1). Then run php artisan migrate again.

Each migration is stored in the migrations table (check your database) so to recreate a table you need to delete the migration record for that table (users) in the migrations table

2
Riaj Ferdous On

General process:

I have lost my 6 hours to solve same problem you faced, but now its like a food to eat.

Step 1: Prerequisites:

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column

Step 2: For Creating Columns:

The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance you may use to add columns to the table:

   Schema::table('users', function (Blueprint $table) {
   $table->string('email');
   });

Step 3 (if needed):

Use the following command in console

php artisan migrate:refresh