Laravel Drop all tables

To efficiently drop all tables in a Laravel project, you can create a custom Artisan command. This approach provides better control and safety compared to raw SQL queries. Follow these steps:


1. Open your Laravel project's root directory in a terminal or command prompt.


2. Create a new Artisan command using the following command:


php artisan make:command DropAllTables


3. Open the generated `DropAllTables.php` file in the `app/Console/Commands` directory.


4. In the `handle` method of the `DropAllTables` command, you can use Laravel's Schema Builder to retrieve a list of all tables and drop them. Here's an example implementation:


use Illuminate\Console\Command;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Schema;


class DropAllTables extends Command

{

    protected $signature = 'db:drop-all-tables';

    protected $description = 'Drop all database tables';


    public function __construct()

    {

        parent::__construct();

    }


    public function handle()

    {

        $connection = config('database.default');

        $tables = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();


        if ($this->confirm("Do you really want to drop all tables from the $connection database?")) {

            DB::beginTransaction();

            try {

                foreach ($tables as $table) {

                    Schema::dropIfExists($table);

                }

                DB::commit();

                $this->info('All tables dropped successfully.');

            } catch (\Exception $e) {

                DB::rollBack();

                $this->error('An error occurred while dropping tables. No changes were made.');

            }

        } else {

            $this->info('Operation cancelled. No tables were dropped.');

        }

    }

}


5. Save the file and close it.


6. Now, you can run the custom command to drop all tables:


php artisan db:drop-all-tables


7. Confirm the action and the command will proceed to drop all tables safely.


This approach utilizes Laravel's built-in features and provides confirmation and transaction handling for added safety. Remember to use it responsibly, as dropping tables will permanently delete all data. Always have backups in place before performing such operations on a production database.