DEV Community

Kachkol Asa
Kachkol Asa

Posted on • Edited on • Originally published at laraveleco.com

How does the defer() function works in Laravel?

Taylor Otwell recently announced the new function in Laravel called defer(). This will just do a very basic overview of how defer() function works and what problems you might have with it.

Identify the problem
Remember the routes you used to have where it needs to fetch something from the API and then perform some actions behind the scenes that the user does not care about but still waits for it? Yeah we all had it at least once, and Laravel knew it way before hence we have laravel's queues to handle those cases. But it's a lot of cumbersome to create a queue to just run a single function.

How defer() function solves it
Whenever you wrap a code in the defer() function, it will run the wrapped code after the response has been sent to the user browser. It makes it easier for the user to navigate without waiting for complex codes that takes a lot of time and the user does not care about them to complete for his response to be sent back to his/her browser.

Laravel makes it easy to run the wrapped code inside the defer() function even if the request fails with the ->always() method.

Using examples and reference: https://laraveleco.com/defer-function-in-laravel/


If you liked this article and want to support, you can do so by buying me a coffee.

Top comments (2)

Collapse
 
fkadeal profile image
Fkadeal Mat

ok so how can we use it on lower version of Laravel

Collapse
 
kachkolasa profile image
Kachkol Asa

You can't, you will need the latest version of Laravel (v11.23) to use the defer() function. Of course you can develop your own utility function of the same functionality as defer() customly but Laravel's defer() function got released very recently in the 11.23 release.