Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncate all tables in laravel using eloquent

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.

like image 979
Mounir Avatar asked Sep 20 '13 04:09

Mounir


People also ask

How to delete all table data in Laravel?

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.

What is truncate () laravel?

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();

How do you delete in laravel eloquent?

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();


1 Answers

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(); 
like image 138
Hao Luo Avatar answered Sep 23 '22 23:09

Hao Luo