Use defer() to Cleanup After a Response

  • Laravel

Starting from version 10, Laravel lets you delay logic until after the response is sent:

1defer(function () {
2 // Clean up temporary files
3 Storage::delete($this->tempFile);
4});

Perfect for non-urgent background work that doesn’t need a queue, like deleting a file, sending emails or storing request analytics.