How to delete data from database in laravel?

by filiberto , in category: PHP Frameworks , 5 months ago

How to delete data from database in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 5 months ago

@filiberto 

To delete data from a database in Laravel, you can use the delete method on the model instance or use the destroy method if you want to delete multiple records. Here's an example:

  1. Deleting a single record:
1
2
$user = User::find($id);
$user->delete();


  1. Deleting multiple records:
1
User::destroy([1, 2, 3]); // Deletes users with IDs 1, 2, and 3


You can also add a condition to the destroy method to delete records based on a specific criteria:

1
User::where('status', 'inactive')->delete(); // Deletes users whose status is 'inactive'


Make sure to import the model at the top of your file using use AppModelsUser; if you are using a different model than the User model in the examples above.