Blog Detail

27

Jun
Run Your Laravel App Code Asynchronously with Laravel Async cover image

arrow_back Run Your Laravel App Code Asynchronously with Laravel Async

Laravel Async is a package that provides a straightforward way to run code asynchronous and parallel based on the Spatie Async wrapper for the Laravel application.

Installation

You can install the Laravel Async package by using Composer:

composer require vxm/laravel-async

The package will automatically register itself.

You can publish the config file (optional) with:

php artisan vendor:publish --provider="VXM\Async\AsyncServiceProvider" --tag="config"

Usage

Run async code

After installation, now you can try running async code via the Async facade:

use Async;

for ($i = 1; $i < 20; $i++) {
    Async::run(function () use ($i) {
        sleep(1);

        return $i;
    });
}

var_dump(implode(', ', Async::wait()));

// Output value may be like:
// string(65) "5, 2, 1, 14, 4, 6, 7, 8, 19, 16, 12, 18, 13, 3, 10, 9, 11, 17, 15"

An async job can be a callable class, anonymous function, or Laravel callback:

use Async;

// run with anonymous function:
Async::run(function() {
    // Do a thing
});

// run with class@method
Async::run('Your\AsyncJobs\Class@handle');

// call default `handle` method if method not set.
Async::run('Your\AsyncJobs\Class');

You can run multiple jobs one time and wait until all are done.

use Async;

Async::run('Your\AsyncJobs\Class@jobA');
Async::run('Your\AsyncJobs\Class@jobB');
Async::run('Your\AsyncJobs\Class@jobC');
Async::run('Your\AsyncJobs\Class@jobD');

// Another way:

Async::batchRun(
    'Your\AsyncJobs\Class@jobA',
    'Your\AsyncJobs\Class@jobB',
    'Your\AsyncJobs\Class@jobC',
    'Your\AsyncJobs\Class@jobD'
);

$results = Async::wait(); // result return from jobs above

Event listeners

When creating asynchronous processes, you can add the following event hooks:

use Async;

Async::run(function () {

    return 123;
}, [
    'success' => function ($output) { 
        // `$output` of job in this case is `123`.
    },
    'timeout' => function () { 
        // A job took too long to finish.
    },
    'error' => function (\Throwable $exception) {
        // When an exception is thrown from job, it's caught and passed here.
    },
]);

// Another way:
Async::run('AsyncJobClass@handleMethod', [
    'success' => 'AsyncJobEventListener@handleSuccess',
    'timeout' => 'AsyncJobEventListener@handleTimeout',
    'error' => 'AsyncJobEventListener@handleError'
]);

Async::batchRun(
    ['AsyncJobClassA@handleMethod', ['success' => 'AsyncJobEventListenerA@handleSuccess']],
    ['AsyncJobClassB@handleMethod', ['success' => 'AsyncJobEventListenerB@handleSuccess']],
    ['AsyncJobClassC@handleMethod', ['success' => 'AsyncJobEventListenerC@handleSuccess']]
);

This package has many great features and options available with code examples. If you want to learn more about this package you can visit its documentation and source code on Github.

Closing Notes

If you are a business and want to leverage Laravel for your next PHP-based web application, CRM Software, E-commerce application, SAAS application, or any custom web application development for your bespoke requirements, you must discover an impeccable team with experience in the Laravel framework. So Codebrisk is here to help you with your tailored requirements regarding Laravel Development. Please feel free to send us an email at rizwan@codebrisk.com or get in touch with us, our business person will get back to you.

Published at : 27-06-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project