[laravel] How to delete all the rows in a table using Eloquent?

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 for documentation on the subject and can't find it!

This question is related to laravel laravel-4 eloquent

The answer is


You can try this one-liner which preserves soft-deletes also:

Model::whereRaw('1=1')->delete();

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

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


The best way for accomplishing this operation in Laravel 3 seems to be the use of the Fluent interface to truncate the table as shown below

DB::query("TRUNCATE TABLE mytable");

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

Solution who works with Lumen 5.5 with foreign keys constraints :

$categories = MusicCategory::all();
foreach($categories as $category)
{
$category->delete();

}
return response()->json(['error' => false]);

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.


In a similar vein to Travis vignon's answer, I required data from the eloquent model, and if conditions were correct, I needed to either delete or update the model. I wound up getting the minimum and maximum I'd field returned by my query (in case another field was added to the table that would meet my selection criteria) along with the original selection criteria to update the fields via one raw SQL query (as opposed to one eloquent query per object in the collection).

I know the use of raw SQL violates laravels beautiful code philosophy, but itd be hard to stomach possibly hundreds of queries in place of one.


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

In my case laravel 4.2 delete all rows ,but not truncate table

DB::table('your_table')->delete();


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.


simple solution:

 Mymodel::query()->delete();

Can do a loop too..

$collection = Model::get();

foreach($collection as $c) {

$c->delete();

}

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()