How to Use Destroy Method in Eloquent for Deleting Records
In Laravel Eloquent, use the
destroy method to delete one or more records by their primary key(s). You can pass a single ID, multiple IDs as arguments, or an array of IDs to destroy, and it will remove those records from the database.Syntax
The destroy method is called on an Eloquent model and accepts one or more primary key values to delete the corresponding records.
Model::destroy($id)- deletes a single record by ID.Model::destroy($id1, $id2, ...)- deletes multiple records by IDs.Model::destroy([$id1, $id2, ...])- deletes multiple records using an array of IDs.
php
Model::destroy(1); Model::destroy(1, 2, 3); Model::destroy([4, 5, 6]);
Example
This example shows how to delete a single user by ID and multiple users by passing an array of IDs using the destroy method.
php
<?php use App\Models\User; // Delete a single user with ID 1 User::destroy(1); // Delete multiple users with IDs 2, 3, and 4 User::destroy([2, 3, 4]);
Output
Records with IDs 1, 2, 3, and 4 are deleted from the users table.
Common Pitfalls
1. Passing non-existent IDs: If you pass IDs that do not exist, destroy will simply ignore them without error.
2. Forgetting to import the model: Always import your Eloquent model with use before calling destroy.
3. Using destroy on model instances: destroy is a static method and expects IDs, not model objects. To delete a model instance, use $model->delete().
php
<?php use App\Models\User; // Wrong: Passing model instance instead of ID $user = User::find(1); User::destroy($user); // This will not work as expected // Right: Pass the ID User::destroy($user->id);
Quick Reference
| Usage | Description |
|---|---|
| Model::destroy(1); | Delete a single record by ID |
| Model::destroy(1, 2, 3); | Delete multiple records by IDs |
| Model::destroy([4, 5, 6]); | Delete multiple records using an array of IDs |
| $model->delete(); | Delete a single model instance |
Key Takeaways
Use
destroy to delete records by their primary key(s) directly on the model.destroy accepts single IDs, multiple IDs as arguments, or an array of IDs.Do not pass model instances to
destroy; use delete() on instances instead.Passing non-existent IDs to
destroy does not cause errors; those IDs are ignored.Always import your model class before calling
destroy to avoid errors.