How to delete an entry from the database Laravel

Learn how to delete a record from a Laravel DB w/ an example: Create a controller, define a route, use Eloquent's delete() method.

Deleting an Entry from the Database with Laravel

Laravel's Eloquent ORM makes it easy to delete entries from the database. All you need to do is get an instance of the model you want to delete and call the delete() method on it. For example, if you have a Post model and want to delete a post with an id of 1, you can do it like this:

$post = Post::find(1);
$post->delete();

This will delete the post from the database. However, if you are using soft deletes, the entry will not be actually removed from the database. Instead, the deleted_at column of the entry will be updated to the current timestamp. This will allow you to restore the entry later if needed.

If you want to delete multiple entries at once, you can use the destroy() method. This method takes an array of ids as an argument and deletes all the entries with those ids. For example, if you want to delete posts with ids 1 and 2, you can do it like this:

Post::destroy([1, 2]);

You can also use the where() method to delete entries that meet certain criteria. For example, if you want to delete all posts that were created more than a month ago, you can do it like this:

Post::where('created_at', '<', CarbonCarbon::now()->subMonth())->delete();

This will delete all posts that were created more than a month ago. It is important to note that this will delete all the entries that meet the criteria, so use it with caution.

Deleting entries from the database with Laravel is easy and straightforward. All you need to do is get an instance of the model you want to delete and call the delete() or destroy() methods on it. You can also use the where() method to delete entries that meet certain criteria.

Answers (0)