Blog Detail

25

Mar
Handle the Export of Large Data Asynchronously in Laravel cover image

arrow_back Handle the Export of Large Data Asynchronously in Laravel

Leyton comes up with an amazing package called Clever Export. The goal of this Laravel package is to execute the exportation to EXCEL large data/records that may cause the crash of the server or a timeout. The idea is to divide the process into sub-operations manageable and easy to perform.

Installation

You can install this package via composer.

compose require leyton/clevexport

After the installation make sure to publish the assets

php artisan vendor:publish --provider="Leyton\ClevExportServiceProvider"

You will find the config/clevexport.php file containing all the configurations needed.

Then you can run your migration

php artisan migrate

Usage

The QueryFinder should be provided with an instance of an object that implements the IseExportable Interface

 $dossierExporter = QueryFinder::getInstance($this->defaultDossierService, $this->transformer);

 PreparingExportJob::dispatch($dossierExporter, $request->all())->delay(now()->addSecond());

A second parameter is optional and if is provided it should implement the ShouldHandleResult It is where you can perform extra work on the results and provide the headers in an ExportTransformed container If the second parameter is not provided then the headers will be the column names selected from the query.

Exportable

class UserExportable implements IsExportable
{

    /**
     * @param array $params
     * @return Builder
     */
    public function query(array $params): Builder
    {
        return  User::select('id', 'name', 'email')
            ->addSelect([
                'title' => Post::selectRaw('SUBSTRING(`content`, 1, 10) as `title`')->limit(1)
            ]);
    }
}

Transformer

class UserTransformer implements ShouldHandleResult
{

    public function transform($data): ExportTransformed
    {
        $data =   $data->map(function(User $user){
            $user->most_commented = optional($user->posts()->withCount('comments')->first())->comments_count;
            $user->comments_count = $user->comments()->count();
            $user->posts_count = $user->posts()->count();
            return $user;
        });

        return  new ExportTransformed(['id', 'name', 'email', 'title', 'Most commented', 'Comments count', 'Posts count'], $data->toArray());
    }
}

For more details about this package, you can visit its complete documentation & source code on Github.

Published at : 25-03-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