Updated: Feb 5, 2020 — 1 min Read — #quick-dip

Normally, if you want to run a task and don't want the user to wait until it's done you'd dispatch a queued job. However, sometimes that task is really simple and short that putting it in a queue might be an overkill.

Using Laravel, you can run such tasks after sending the response to the user. It works by keeping the PHP process alive to run the tasks after closing the connection with the browser. You can do that using:

Terminable Middleware.

Terminating callbacks (e.g. App::terminating(function(){ }) )

) Job::dispatchAfterResponse() using Laravel v6.14.0 or higher.

If you have a job called ClearCache, you can run it after the response is sent like this:

function store (Response $response) { ClearCache::dispatchAfterResponse(); return view( 'success' ); }

Remember, this is only a good idea if the task is really short. For long running tasks, dispatching to queue is recommended.