How to delete a model in Laravel

Laravel tutorial: learn how to delete models using Eloquent ORM & example.

Deleting a Model in Laravel

Laravel makes it easy to delete a model instance. To delete a model, you must first locate the instance of the model in the database. To do this, you can use the Eloquent find method to locate the model using its primary key. Once the model is located, the delete method can be used to delete the model from the database.


$user = AppUser::find(1);
$user->delete();

The delete method will fire the deleted event and call the deleted model's delete method. If the model instance has global scopes, they will be ignored when calling the delete method.

If you would like to delete a model only if it exists, you may use the forceDelete method. This method will bypass the soft deletes and force the model instance to be deleted:


$user = AppUser::find(1);

if ($user) {
    $user->forceDelete();
}

The forceDelete method will also fire the deleted event and call the deleted model's delete method. It will also ignore any global scopes when deleting the model.

If you are using soft deletes, the model will actually not be deleted, but it will be "soft deleted". To perform a soft delete, you may use the delete method on the model:


$user = AppUser::find(1);
$user->delete();

When a model is soft deleted, it will be preserved in the database, but all queries to the model will not include the soft deleted model. To completely remove a model from the database, you must use the forceDelete method.

If you are soft deleting a model, you may restore it using the restore method. This method will bring the model back from the deleted state into an active state:


$user = AppUser::withTrashed()->find(1);

$user->restore();

The restore method will fire the restored event and call the restored model's restore method. Global scopes will still be applied when calling the restore method.

Answers (0)