How to delete all the rows in a table using Eloquent?
You can use Model::truncate()
if you disable foreign_key_checks
(I assume you use MySQL).
DB::statement("SET foreign_key_checks=0");
Model::truncate();
DB::statement("SET foreign_key_checks=1");
Laravel 5.2+ solution.
Model::getQuery()->delete();
Just grab underlying builder with table name and do whatever. Couldn't be any tidier than that.
Laravel 5.6 solution
\App\Model::query()->delete();
The reason MyModel::all()->delete()
doesn't work is because all()
actually fires off the query and returns a collection of Eloquent objects.
You can make use of the truncate method, this works for Laravel 4 and 5:
MyModel::truncate();
That drops all rows from the table without logging individual row deletions.
I've seen both methods been used in seed files.
// Uncomment the below to wipe the table clean before populating
DB::table('table_name')->truncate();
//or
DB::table('table_name')->delete();
Even though you can not use the first one if you want to set foreign keys.
Cannot truncate a table referenced in a foreign key constraint
So it might be a good idea to use the second one.