Delete all data from laravel Model

In many applications, we often need to clear all records from a database table. For example, tables storing temporary data like session logs, cache records, or daily reports require regular cleanup to maintain performance. In Laravel, we can delete all data from an Eloquent model easily. This removes all rows while keeping the table structure intact.

A common use case is a logging system where you store user activity for a day. At the end of each day, you can delete all data from the Eloquent model to start fresh, ensuring efficient storage and faster queries.

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.

Using truncate() / delete() Method

The truncate method empties the 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 deleted and reset its indexed while the delete method deletes all the data without index reset.

Deleting data with Queries

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

We first set conditions that cannot fail, such as ensuring the primary key is not null or empty. Then, we select the data and perform the delete operation.

Conclusion

In this article, we have taken a few examples of deleting all data from a specific model using a query, model instance, or even DB facade.

For managing deletions gracefully in Laravel, you can explore adding soft delete to every model and migration by default.