Delete all Laravel models in a table
June 26, 2022 ‐ 1 min read
I'm assuming you know that removing all the Laravel models from a table is a dangerous operation. You may not only delete the models you expect, but also other models with a foreign key with cascading delete.
That being said. My first assumption was to run Model::all()->delete();
, however this spawned an exception with message: 'Method Illuminate\Database\Eloquent\Collection::delete does not exist.'
It turns out that all()
already runs the SQL query and returns a collection. Instead you can use the truncate()
method to remove all the models in a table.
You can either call this method directly on the model:
<?php
Model::truncate();
Or via the DB
facade:
<?php
DB::table('models')->truncate();