Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check If a Column Exists in Laravel Migration File

Tags:

sql

php

laravel

Already I have a table name table_one. Now I want to add two more columns to it. Everything works fine so far. But in my method, I want to check a column exists or not in my table like dropIfExists('table').

/**  * Run the migrations.  *  * @return void  */ public function up() {     Schema::table('table_one', function (Blueprint $table) {         $table->string('column_one')->nullable();         $table->string('column_two')->nullable();     }); }  /**  * Reverse the migrations.  *  * @return void  */ public function down() {     Schema::table('table_one', function (Blueprint $table) {         // in here i want to check column_one and column_two exists or not         $table->dropColumn('column_one');         $table->dropColumn('column_two');     }); } 
like image 450
Md.Sukel Ali Avatar asked Jan 14 '19 05:01

Md.Sukel Ali


People also ask

How do you check if table exists in a migration?

Solution to this is Schema::hasTable() method. So, if table flights does not exist, then we create it. Of course, it can be used in a positive way – for example, if we want to add a new column to existing table, then we may check if table does exist.

What is up and down in laravel migration?

A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.


2 Answers

You need something just like this

  public function down()     {         if (Schema::hasColumn('users', 'phone'))         {             Schema::table('users', function (Blueprint $table)             {                 $table->dropColumn('phone');             });         }     } 
like image 62
Ismoil Shifoev Avatar answered Sep 17 '22 07:09

Ismoil Shifoev


You could make your own 'dropColumnIfExists()' function that checks the column existence then drop it:

function myDropColumnIfExists($myTable, $column) {     if (Schema::hasColumn($myTable, $column)) //check the column     {         Schema::table($myTable, function (Blueprint $table)         {             $table->dropColumn($column); //drop it         });     }  } 

And use it on 'down()' function like this:

public function down() {     myDropColumnIfExists('table_one', 'column_two');     myDropColumnIfExists('table_one', 'column_one'); } 
like image 22
Marco Aurelio Avatar answered Sep 17 '22 07:09

Marco Aurelio