Laravel How to Delete Record

Laravel: how to delete a record using Eloquent ORM w/ example.

Deleting Records in Laravel

Deleting records in Laravel is quite straightforward. All you have to do is call the delete() method of the Eloquent model. The delete() method will delete the model from the database and return the number of deleted rows. Let's look at an example of deleting a record.


// Retrieve the record from the database
$user = User::find(1);

// Delete the record from the database
$deletedRows = $user->delete();

The $deletedRows variable will contain the number of deleted rows. If the record was successfully deleted, then $deletedRows will be 1.

If you need to delete multiple records, you can use the destroy() method. This method takes an array of ids and will delete all the records that match the given ids.


// Delete multiple records
$deletedRows = User::destroy([1, 2, 3]);

The $deletedRows variable will contain the number of deleted records. If all the records were successfully deleted, then $deletedRows will be 3.

If you need to delete records based on a condition, you can use the where() method to filter the records before deleting them. For example, if you want to delete all users who are older than 18, you can do this:


// Delete records based on a condition
$deletedRows = User::where('age', '>', 18)->delete();

The $deletedRows variable will contain the number of deleted records. If all the records were successfully deleted, then $deletedRows will be the number of records that matched the given condition.

Finally, if you need to delete all the records in a table, you can use the truncate() method. This method will delete all the records in the table and reset the auto-incrementing ID to 0.


// Truncate a table
User::truncate();

That's all you need to know about deleting records in Laravel. As you can see, it's quite easy to delete records with Eloquent. Happy coding!

Answers (0)