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.
In the first example, we are going to use the truncate() function, which is used to delete all the records. In the second example, we will delete records on the basis of the id. So we will specify some id and use the delete() function to delete all the records of that particular id.
From the Laravel Docs https://laravel.com/docs/5.6/queries#deletes says: If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method: DB::table('users')->truncate();
Laravel Eloquent Deleting You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete. To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete();
NOTE:
doctrine/dbal
Package is Required for Performing this Operations
So Make Sure that is Installed composer require doctrine/dbal
$tableNames = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With