"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How does the defer() function works in Laravel?

How does the defer() function works in Laravel?

Published on 2024-11-06
Browse:767

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/

Release Statement This article is reproduced at: https://dev.to/kachkolasa/how-does-the-defer-function-works-in-laravel-1a9e?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3