What is laravel concurrency() and defer() function ?

What is laravel concurrency() and defer() function ?

By Qisti

Both function have been introduced in laravel 11 before and now still available in laravel 12. So what is this and why it important for you to know.

First of all, purpose of concurrency() function is to run multiple logic at a time without run it 1 by 1, i repeated it myself we can run multiple logic in a time, just calling the function and we able to save time to load a page since it run some logic concurrenly to reduce waiting time.

even it nice since it can do that, as a profesional developer we need to take consideration before use it because it may harm our server performance if not use it at the right place and being use without control.

enought of talking, here are example u can try:

use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;
[$userCount, $MigrationCount] = Concurrency::run([
 fn () => DB::table('users')->count(),
 fn () => DB::table('migrations')->count(),
]);
instead of run it 1 by 1, assign it all inside concurrentcy function

Second function you need to know is defer(), it allow you to run some logic on background without waiting it to being done. Means your page will fully load without need to wait the logic in defer() to being done.

why we need it? , in real world in some request we may want skip some logic and go to the page faster. example logic we may skip are can be email logic, audit logic, push notification and more.

here are the example :

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeMail;
use App\Models\User;

public function store(Request $request)
{
    $user = User::create($request->all());

    // Defer sending the welcome email until after the response
    defer(function () use ($user) {
        Mail::to($user->email)->send(new WelcomeMail($user));
    });

    // Immediately redirect to product page
    return redirect()->route('product.show', ['product' => 123]);
}
not like an old style, we need to send job into a queue even just for a simple task