Delete
Delete an existing model
Controllers with any of these Traits have method destroy($id)
which a route can connect to for updating a model.
<?php
// ...
Route::delete('/tasks/{id}', 'TaskController@destroy');
Note
If the target model is not found, method
notFoundError()
is called which by default returns a 404 response.
Before destroy
To catch the model before it is destroyed, implement method beforeDestroy( ... )
.
<?php
//...
public function beforeDestroy(Illuminate\Database\Eloquent\Model $data) {
// do something with/on $data
}
Tip
- If the method returns a non-null value, the destroy process is terminated and the returned value is sent to the client as the response.
Before response
After the model has been deleted, it can be accessed with the beforeDestroyResponse( ... )
method before it is sent to the client.
<?php
// ...
public function beforeDestroyResponse(Illuminate\Database\Eloquent\Model &$data) {
// do something with/on $data
}
Tip
If the method returns a non-null value, the returned value is sent to the client as the response.
Exceptions
Exceptions are caught in the destroy()
method and the destroy process is rolled back. To perform more operations when rolling back, implement method rollbackDestroy( ... )
.
<?php
// ...
public function rollbackDestroy(Illuminate\Database\Eloquent\Model $model) {
// do some further rolling back
}
Destroy many
Method destroyMany()
is also available to delete several models in a single request. An array of the id
s of the models should be provided in the request body on key ids
.
<?php
// ...
Route::post('tasks/delete-many', 'TaskController@destroyMany');
Methods beforeDestroyMany(&$data)
, rollbackDestroyMany($ids)
and beforeDestroyManyResponse($deletedCount)
are available.
Force destroy
Method forceDestroy($id)
permanently deletes a model. Like the destroy($id)
method, it also has supporting methods such as beforeForceDestroy($data)
, rollbackForceDestroy($model)
and beforeForceDestroyResponse($model)
.
Restore destroyed
Method restoreDestroyed($id)
restores a soft-deleted model. It has supporting methods such as beforeRestoreDestroyed($model)
, rollbackRestoreDestroyed($model)
and beforeRestoreDestroyResponse($model)
.
Updated over 6 years ago