Laravel how to remove
"Learn how to delete records in Laravel with an example of deleting a post from a blog."
Using Eloquent ORM to Delete Records in Laravel
Laravel Eloquent ORM provides an easy way to access and manipulate the data stored in the database such as creating, updating, and deleting records. In this article, we will look into how to delete records using Eloquent ORM.
To delete a record in the database, we can use Eloquent’s delete
method. The delete
method will delete the specified record from the database. It takes an optional argument which is the id of the record. If no id is specified, all the records in the table will be deleted.
// delete a single record $user = User::find(1); $user->delete(); // delete multiple records User::where('age', '>', 18)->delete();
Sometimes, you may want to delete the record without retrieving it first. To do this, you can use the destroy
method. The destroy
method takes the id of the record (or an array of ids) as the argument and deletes the record directly from the database.
// delete a single record User::destroy(1); // delete multiple records User::destroy([1, 2, 3]);
Another way to delete records is to use the delete
method on the query builder. This is useful when you want to delete records based on certain conditions. The delete
method takes the same argument as the where
clause.
// delete records User::where('age', '>', 18)->delete();
Finally, you can also use the truncate
method to delete all the records in the table. The truncate
method will delete all the records without firing any delete events. This is useful when you want to delete all the records in the table quickly.
// delete all records User::truncate();
In this article, we looked at how to delete records in Laravel using Eloquent ORM. We saw various methods such as delete
, destroy
, and truncate
that can be used to delete records. We also saw how to delete records based on certain conditions.