loading...

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

nromero125 profile image Nelson Romero ・1 min read

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

Discussion

pic
Editor guide
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
juandamartn 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!