Example, I already type command migration and all tables are generated in database but what if I want to remove specific columns in database? The article below we will discuss how to remove the exsiting column table in migration file. This short tutorial will show you with various example how to drop the column in Laravel migration. You also can easily drop the columns from with database in Larvel 6, Larvel 7 Laravel 8 and Laravel 9.
Let'see below example we will show you easily way to remove column using migration file. These three ways below help you to remove columns from database.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ModArticleTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn('description');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
For mulitple drop the columns in migration file by adding value as an array.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ModArticleTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn(['keywords','description']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Sometimes to prevent error occure while doing delete column in table we have to check if there existing column in the tabel. By following code help you to check if there is exist column then allow to drop the column.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ModArticleTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (Schema::hasColumn('keywords'))
{
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn('keywords');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Thank for reading this short article, hope it would help your project. Have a nice day!!
You might also like...
Laravel PHP Laravel 9As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him