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:
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.
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.
Top comments (5)
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.
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?
I was exactly looking for this, thank you!
Thanks, that was helpful.
That helped, thanks!