How to drop table in Laravel migration?

by ryan.murray , in category: PHP Frameworks , 2 years ago

How to drop table in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by wilmer.lemke , a year ago

@ryan.murray 

To drop a table in Laravel migration, you can use the dropIfExists method on the Schema facade.


Here's an example of how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use IlluminateSupportFacadesSchema;

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::dropIfExists('table_name');
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
}


The dropIfExists method will check if the table exists before attempting to drop it, so it is safe to use in cases where the table may or may not exist.


Note that this method is only available in Laravel 8.0 and higher. If you are using an earlier version of Laravel, you can use the drop method instead, which works in the same way but does not check if the table exists before attempting to drop it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use IlluminateSupportFacadesSchema;

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::drop('table_name');
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
}


by hal.littel , 8 months ago

@ryan.murray 

To drop a table in Laravel migration, you can use the Schema facade's dropIfExists() method. Here is an example of how to drop a table in a migration file:

  1. Open the migration file in the database/migrations directory.
  2. Inside the up() method, use the Schema::dropIfExists() method followed by the table name as shown below:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use IlluminateDatabaseMigrationsMigration;
use IlluminateSupportFacadesSchema;

class DropExampleTable extends Migration
{
    public function up()
    {
        Schema::dropIfExists('example');
    }

    // ...

}


  1. Save the migration file.
  2. Run the migration using the following command:
1
php artisan migrate


This will drop the table specified in the dropIfExists() method from the database.