Adding a New Field without Losing Data in Laravel
Normally when we are adding a new field to the migration process in Laravel, our existing data is removed. But I am going to show you the process without losing any data. We can add new columns or fields to our existing table. Please read carefully step by step.
So, let's start
Step 1:
Suppose we already have a table named 'table1'.
We need to create a new model for adding new columns.
Run this on CMD.
php artisan make:migration addnewcolumn_table1_table
Step 2:
Now add this on up() function.
Schema::table('table1', function (Blueprint $table) { if(!Schema::hasColumn('table1','new_field')){ $table->string('new_field')->after('id'); } });
Step 3:
Run this on CMD
php artisan migrate:refresh.
Conclusion:
Hope it can help you to add new fields without losing data. This is very important in Laravel development. Please read and share your thoughts on the same in the comment section. Happy coding.