Hello Artisan
In this laravel migration tutorial i am going to show you how we can add new column to our table without losing database. We don't do it manually. We will create it with laravel migration commands.
Sometimes after creating model and migration we need to change our table column. That time if you run migrate:refresh or migrate:fresh command then laravel delete our all database data.
In this quick example i will show you laravel migration update table data without losing our previous data. So let's see how we can create changing database schema without losing data.
Suppose think we will add a new column product_code in our products table after qty column. So run below command.
php artisan make:migration add_new_column_to_products_table
After running this above command you will get below file.
database\migration\add_new_column_to_products_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddNewColumnToProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
if (!Schema::hasColumn('products', 'product_code')){
$table->string('product_code')->after('qty');
};
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn(['product_code']);
});
}
}
Now you can run migrate command to add this new field. Simply you can run below command to auto add a new field.
php artisan make:migration add_product_code_to_products_table --table=products
Hope it can help you. Laravel Migration example tutorial, in this tutorial you have learned how to add new column to a table without losing data.
#laravel #laravel-7 #migration-tips