My guess was to use the following syntax:
MyModel::all()->delete();
But that did not work. I\'m sure it\'s super simple, but I\'ve searched
I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate()
resets. I also didn't want to use DB::
anything because I wanted to operate directly off of the model object. So, I went with this:
Model::whereNotNull('id')->delete();
Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id
column exists and is never null. I don't know if this is the best choice, but it works for my purposes.
You can try this one-liner which preserves soft-deletes also:
Model::whereRaw('1=1')->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 wasn't able to use Model::truncate()
as it would error:
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint
And unfortunately Model::delete()
doesn't work (at least in Laravel 5.0):
Non-static method Illuminate\Database\Eloquent\Model::delete() should not be called statically, assuming $this from incompatible context
But this does work:
(new Model)->newQuery()->delete()
That will soft-delete all rows, if you have soft-delete set up. To fully delete all rows including soft-deleted ones you can change to this:
(new Model)->newQueryWithoutScopes()->forceDelete()
simple solution:
Mymodel::query()->delete();
There is an indirect way:
myModel:where('anyColumnName', 'like', '%%')->delete();
Example:
User:where('id', 'like' '%%')->delete();
Laravel query builder information: https://laravel.com/docs/5.4/queries