Site icon Naya Gyan | Knowledge that never get expired

Create large CSV file, Archive and send it through email using Laravel 9

Download large CSV file using Laravel 9

Create large CSV file, Archive and send it through email using Laravel 9

Using Laravel 9, you can use chunking to create a large CSV file, compress it, and send it as an email attachment:

1. Install the required dependencies:

composer require "league/csv:^9.0" // For working with CSV files

composer require "phpmailer/phpmailer:^6.5" // For sending emails

2. Create a route and controller method to handle the file creation, compression, and email sending.

For example, in your routes/web.php file, add a route like this:

use App\Http\Controllers\DownloadCSVController;

Route::get('/send-large-csv', [DownloadCSVController::class, downloadata]);

3. Generate the controller and its method:

php artisan make:controller DownloadCSVController

4. Open the app/Http/Controllers/DownloadCSVController.php file and update the sendBigCSV method as follows:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Mail;

use League\Csv\Writer;

use PHPMailer\PHPMailer\PHPMailer;

class DownloadCSVController extends Controller

{

    public function downloadata()

    {

        // Generate a large CSV data (e.g., 100,000 rows)

        $totalRows = 100000;

        $chunkSize = 5000;

        $csvData = [];

        for ($i = 1; $i <= $totalRows; $i++) {

            $csvData[] = [

                'Name ' . $i,

                'Email ' . $i,

‘Address’ . $i

            ];

            if ($i % $chunkSize === 0) {

                // Create a chunk and save it to the CSV file

                $this->saveChunkToCSV($csvData, $i / $chunkSize);

                // Reset the chunk data array

                $csvData = [];

            }

        }

        // Save the remaining chunk if any

        if (!empty($csvData)) {

            $this->saveChunkToCSV($csvData, ($totalRows / $chunkSize) + 1);

        }

        // Compress the CSV file

        $zipFile = storage_path('app/big_csv_file.zip');

        $zip = new \ZipArchive();

        $zip->open($zipFile, \ZipArchive::CREATE);

        $zip->addFile(storage_path('app/big_csv_file.csv'), 'big_csv_file.csv');

        $zip->close();

        // Send the compressed CSV file via email

        $mail = new PHPMailer(true);

        $mail->isSMTP();

        // Configure your SMTP settings

        $mail->Host = 'smtp.example.com';

        $mail->SMTPAuth = true;

        $mail->Username = 'your_email@example.com';

        $mail->Password = 'your_password';

        $mail->SMTPSecure = 'tls';

        $mail->Port = 587;

        $mail->setFrom('your_email@example.com', 'Your Name');

        $mail->addAddress('recipient@example.com', 'Recipient Name');

        $mail->Subject = 'Big CSV File';

        $mail->isHTML(false);

        $mail->addAttachment($zipFile, 'big_csv_file.zip');

        $mail->send();

        return 'Big CSV file sent successfully!';

    }

    private function saveChunkToCSV(array $chunkData, int $chunkNumber)

    {

        $csv = Writer::createFromPath(storage_path('app/big_csv_file.csv'), 'a');

        $csv->setOutputBOM(Writer::BOM_UTF8); // Optional: Add UTF-8 BOM

        if ($chunkNumber === 1) {

            $csv->insertOne(['Name', 'Email']); // Insert header only for the first chunk

        }

        $csv->insertAll($chunkData);

    }

}

Make sure your email provider’s details are added to the SMTP settings.

To initiate the process of creating the large CSV file, chunking it, compressing it into a ZIP file, and emailing it, access the /send-big-csv URL in your web browser or request that route.

This code will create an enormous CSV record by utilizing chunk procedure, save each lump to a CSV document, pack the CSV record into a Compress record, and send it as an email connection utilizing the PHPMailer library.

Exit mobile version