Delete All Records from Table in Laravel Eloquent
In this section, we are going to learn about the deletion of all the table records. We will use Laravel Eloquent to do this. We can use various versions of Laravel like 6, 7, and 8 to delete all records from the table. Laravel includes Eloquent, which is an object-relational mapper. Using Laravel Eloquent, we can easily interact with the database. A model corresponds to each table of the database. Using the corresponding model, we can easily interact with that table. Eloquent is used to easily get the records from the database table because using this, we can also add, edit and remove records from the table. Suppose we will cache all our records. 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. In the second example, we will delete records on the basis of the id. So we will specify some id and use the delete() function to delete all the records of that particular id. If we are using the truncate() function of delete all the table records, then after deletion, the increment value will reset to 1, which is the initial position. But if we are using the delete() function to delete the records, then after deletion, the value of increment will not reset to 1.
This can be called a difference between delete and truncate. So basically, we should choose the truncate() function if we try to delete and reset all the things in the table. If our table contains a primary column and it is set to auto-increment, we should not use the delete() function because, in this case, the value of auto-increment will not get reset. In the third example, we are trying to delete records on the basis of condition. In the fourth example, we will put the table name and use the delete() function to delete all the records from the table.
Now our above code is ready to run. When we run it, we will be able to delete the table row.