truncate all tables in laravel using eloquent

Mounir picture Mounir · Sep 20, 2013 · Viewed 35.6k times · Source

Is there a way I could truncate all the tables in a db using eloquent or fluent in laravel 4? I do not want to specify table names, I just want to truncate all the tables. In other words empty all the tables.

Answer

Hao Luo picture Hao Luo · Sep 20, 2013

NOTE: doctrine/dbal Package is Required for Performing this Operations

So Make Sure that is Installed composer require doctrine/dbal

1. Get all the table names

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

2. Loop through the array of table names and truncate with Schema Builder

foreach ($tableNames as $name) {
    //if you don't want to truncate migrations
    if ($name == 'migrations') {
        continue;
    }
    DB::table($name)->truncate();
}

Help: If you have Got Some Error Such as

SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint

You Can disable foriegn Key Checks

Schema::disableForeignKeyConstraints();

and make sure to ReEnable it

Schema::enableForeignKeyConstraints();