Sometimes we need to delete all the data from a table. Like some tables are just to store temporary data. So we need to delete or empty the table using a specific time or event.
Laravel or Eloquent has many methods from query to static from removing all records from the table like DB class with delete(), truncate, or query delete method.
In this example, we will use a few examples to empty and reset the table or remove all data.
The truncate method empties entire table and deletes all existing records. You just have to perform the truncate() or delete() method on the model instance. It will automatically remove all the data and reset indexes.
User::truncate(); //OR User::delete();
Here, both methods will remove all the data from the user model but in the truncate method, data is being deleted and reset it's indexed while the delete method deletes all the data without index reset.
Using the query method, we set a condition that selects all data and then performs delete operations. Let's take an example of this method.
User::whereNotNull('id')->delete(); //OR User:where('id', 'like' '%%')->delete(); //OR DB::table('users')->delete();
Here, first of all, we set conditions that can't fail like the primary key can not be null or can not be empty so we select all the data and then perform the delete operation.
In this article, we have taken a few examples to delete all data from a specific model using a query, model instance, or even DB facade.
Ask anything about this examples