Our records will be automatically deleted from the cache if users delete all the records from the table. But we can delete it from the cache only if we are using the model of Laravel Eloquent. In the first example, we are going to use the truncate() function, which is used to delete all the records.
Laravel Eloquent Deleting To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete(); Alternatively, you can specify a primary key (or an array of primary keys) of the records you wish to delete via the destroy() method: User::destroy(1); User::destroy([1, 2, 3]);
To delete a whole model collection in Laravel you can make use of the "delete()" method on the collection instance itself.
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.
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();
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With