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/
The above is the detailed content of How does the defer() function works in Laravel?. For more information, please follow other related articles on the PHP Chinese website!