Running a task after the response is sent

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:

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

function store(Response $response)
{
 // Do some work

 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.

Hey! 👋 If you want to receive updates on what I'm up to, I host a newsletter on my website themsaid.com and would love to have you.

You can also follow me on Twitter, I regularly post about all things Laravel including my latest video tutorials and blog posts.

By Mohamed Said

Hello! I'm a full-stack web developer working at Laravel. In this publication, I share everything I know about Laravel's core, packages, and tools.

You can find me on Twitter and Github.

This site was built using Wink. Follow the RSS Feed.