Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to Laravel and I create a users table using php artisan migrate command:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('username');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();

    });

After that I just needed to change the username column as first_name then I change the schema as follows:

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

If I run the php artisan migrate command again, it says Nothing to migrate, then I used rollback, and I lose all table data.. How can I edit table structure without affecting my data? I hate Laravel doc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
757 views
Welcome To Ask or Share your Answers For Others

1 Answer

Let's start with your schema. Your table name is users. It contains a column named username and you want to change it to first_name without losing existing data. You need to create a new migration for this change.

php artian make:migration rename_columns_to_users_table --table=users

A new migration file will be created in your migrations directory. Open it and change it like this:

Schema::table('users', function ($table) {
    $table->renameColumn('username', 'first_name');
});

Save it and then again run

php artisan migrate

You column name will be renamed immediately without losing your old data. Hope you got it now.

You will find more details here: https://laravel.com/docs/5.3/migrations#renaming-columns


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...