DEV Community

Update existing table's column with migration without losing data in Laravel

M H Hasib on May 20, 2021

Before going to start our coding we need to know about Laravel Migration and how it helps us. First of all, if we want to build a project. We need...
Collapse
 
fatimaalmashhor profile image
Fatima Almashhor •

Thank you for this . it save my life.

Collapse
 
brian001 profile image
Brian Kanyi Karanja •

Well discussed. It worked for me. Thank you

Collapse
 
mahmudulhsn profile image
M H Hasib •

Thanks.

Collapse
 
dgrinderhz profile image
Hassan Zekkouri •

Thank you. It saved me time.

Collapse
 
mukul98s profile image
Mukul Sharma •

I though with ORM it's only one way. Thanks for this great article.

Collapse
 
krognome profile image
krognome •

So I'm pretty damns sure if I run php artisan migrate it will without any question run all my migration files and delete all of the data. I see people thanking you here like they did not lose all their data but it always removes all the data every time I run that command. So I simply run the 1 migration file with: php artisan migrate --path=/database/migrations/full_migration_file_name_migration.php

Collapse
 
jackleemmerdeur profile image
JackLeEmmerdeur • • Edited

I just tried this. Before I always used php artisan migrate:refresh, but I needed schema altering with data retention.

For me php artisan migrate only applied the new migration and left the data of unmodified tables untouched, opposed to the above refresh-modifier.

Maybe it has been, like you described, in an old Laravel version?
If unsure there is also php artisan migrate --pretend. It shows the SQL the migrations would produce without executing them.

Collapse
 
mahmudulhsn profile image
M H Hasib • • Edited

php artisan migrate will execute the files which is not in migrations table. Please read the documentation carefully.

Collapse
 
inimist profile image
Arvind Kumar •

Thanks!

Collapse
 
mahmudulhsn profile image
M H Hasib •

Welcome Brother.

Collapse
 
vitalijalbu profile image
vit •

So basically guys, if I try to add phone_number inside the users migration file 1, it will drop table and create another one? So my data will be lost

Collapse
 
tanvirprince profile image
Tanvir Rahman Prince •

Thanks. This is very helpful

Collapse
 
mahmudulhsn profile image
M H Hasib •

You are welcome <3