EliyaCohen's avatar

Change tables structures with migration without losing data?

Hi,

Is there a way to keep the data when I migrate and change the structure of some tables?

I can't do

php artisan migrate

because it won't update the existing tables and I can't use

php artisan migrate:refresh

because It'll lose my data.

0 likes
7 replies
ohffs's avatar

When you say 'because it won't update the existing tables' - what do you mean?

michaeldyrynda's avatar

How did the data get there? If it's something that is seeded, then it shouldn't matter. If it's input as part of entering data into your application through testing, just add and run another migration which alters the structure of the tables.

nfauchelle's avatar
Level 11

@EliyaCohen You create another migration to alter tables.

So when you first make the table, you'll create all the fields etc.

If you want to add another column, or change a column then you create a NEW migration. If you just edit the old one then running php artisan migrate wont do anything.

3 likes
raziel79's avatar

You must create new migration for example, if you have "articles" table and you want to add a new column " excerpt" you run this:

  • make new migration file, this create a new file with up() and down() methods:

php artisan make:migration add_column_exceprt_to_articles --table="articles"

  • open up migration files in database/migrations (Laravel 5.3)

  • edit migration files xxxx_xxx__xxx__xxx_add_column _excerpt_to_articles

  • Edit up method for example

$table->string('excerpt'); // or $table->text('excerpt') if you want a text field instead varchar field

  • running php artisan migrate

here you go, you have new column without losing data.

Best ;)

23 likes
carevaloq87's avatar

Also if you are just renaming a field on a table you will need to do this inside up method:

Schema::table('table_name', function (Blueprint $table) { $table->renameColumn('from','to'); });

Be aware of Schema::table instead of Schema::create , and make sure that you include doctrine/dbal with composer require doctrine/dbal

thanks @raziel79

1 like

Please or to participate in this conversation.