DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Nelson Romero
Nelson Romero

Posted on

How to change tables structures with migration without losing your data in Laravel

This is something that I had always asked myself. "How to add a new column to a table without having to go directly to the database or rollback the migrations?"

Laravel does not generate the migrations automatically through the models as Django or Entity Framework does, but we need to do it manually.

Imagine that you have an application in production and you need to add a new column to the user table. Instead of rollback your migrations (which would cause the data to be lost) you can create a new migration to update the existing table.

Let's go

We have the initial migration of the user table and we want to add a column called picture:
Initial Migration

We execute the following command:

$ php artisan make:migration add_picture_column_to_user_table --table=users

This command would create a new migration file in which we would add our new column.
New Migration

Then run the migrations using php artisan migrate and that's all. You'll have this new column in your users table without losing previously stored data.

Database Screenshot

Top comments (6)

Collapse
 
informationdose profile image
informationdose

what about multiple column addition? how we can achieve this? do we need to write the command every time or can we achieve this using 1 command only? actually I am making a mockup website of this website shilajit4u.pk/ I need to add multiple fields in DB.

Collapse
 
fatemefa profile image
Fateme Fa

Thank you for your help, but I have a question.
for every little change in tables or columns, should we create a second migration file and write our code down there? and after that, can we remove the second migration file or not?

Collapse
 
juanda_dev profile image
Juan MartΓ­nez

I was exactly looking for this, thank you!

Collapse
 
duncankishira profile image
Duncan Kishira

Thanks, that was helpful.

Collapse
 
hackernewbie profile image
Rajiv Verma

That helped, thanks!

New programmer and javascript

Stop by this week's meme thread!