Logo

dev-resources.site

for different kinds of informations.

Building a Quick CSV Export Command in Laravel

Published at
1/13/2025
Categories
laravel
backend
php
webdev
Author
iheb_jabri
Categories
4 categories in total
laravel
open
backend
open
php
open
webdev
open
Author
10 person written this
iheb_jabri
open
Building a Quick CSV Export Command in Laravel

Image description

Building a Quick CSV Export Command in Laravel

When working with Laravel applications, you might find yourself needing to export data to a CSV file. Whether you're building a reporting feature or simply exporting data for analysis, itā€™s essential to implement a solution that is both efficient and straightforward.

Hereā€™s a recommended approach for creating a quick CSV export command in Laravel. This method uses Laravelā€™s chunking functionality to handle large datasets gracefully, writing directly to the output stream with PHPā€™s fputcsv function.

Why This Approach?

  1. Efficiency: By leveraging Laravelā€™s chunking, you process the data in smaller batches, reducing memory usage.
  2. Scalability: You can export large datasets without running into memory issues.
  3. Simplicity: Using fputcsv ensures that CSV formatting is handled correctly without needing additional libraries.

Code Example

use Illuminate\Database\Eloquent\Collection;

$chunk = 500; // Number of records per chunk
$output = fopen('php://stdout', 'wb+'); // Open a stream to StdOut

// Write the CSV headers
fputcsv($output, ['email', 'name']);

// Query the data and write to CSV in chunks
User::select(['email', 'name'])
    ->chunk($chunk, function (Collection $users) use ($output) {
        $users->each(
            fn($user) => fputcsv($output, [$user->email, $user->name])
        );
    });
Enter fullscreen mode Exit fullscreen mode

Breaking Down the Code

1. Define the Chunk Size

The $chunk variable determines how many records are processed in each iteration. Adjust this number based on your dataset size and memory availability.

$chunk = 500;
Enter fullscreen mode Exit fullscreen mode

2. Open a Stream to StdOut

Using php://stdout, you can write directly to the output stream. This is particularly useful for commands that generate CSV exports, as the output can be piped directly to a file or another process.

$output = fopen('php://stdout', 'wb+');
Enter fullscreen mode Exit fullscreen mode

3. Write the CSV Headers

Before writing the data rows, define the CSV headers with fputcsv.

fputcsv($output, ['email', 'name']);
Enter fullscreen mode Exit fullscreen mode

4. Query the Data in Chunks

Use Laravelā€™s chunk method to process the data in smaller batches. This prevents memory exhaustion when dealing with large datasets.

User::select(['email', 'name'])
    ->chunk($chunk, function (Collection $users) use ($output) {
        $users->each(
            fn($user) => fputcsv($output, [$user->email, $user->name])
        );
    });
Enter fullscreen mode Exit fullscreen mode

5. Write Each Row

For each user in the chunk, use fputcsv to format and write their data as a CSV row.

fn($user) => fputcsv($output, [$user->email, $user->name]);
Enter fullscreen mode Exit fullscreen mode

Use Case: Artisan Command

You can encapsulate this functionality within an Artisan command, allowing you to execute the export with a single terminal command. Hereā€™s how you can structure your Artisan command:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use App\Models\User;

class ExportUsersToCsv extends Command
{
    protected $signature = 'export:users';
    protected $description = 'Export users to a CSV file';

    public function handle()
    {
        $chunk = 500;
        $output = fopen('php://stdout', 'wb+');

        // Write the CSV headers
        fputcsv($output, ['email', 'name']);

        // Query the data and write to CSV in chunks
        User::select(['email', 'name'])
            ->chunk($chunk, function (Collection $users) use ($output) {
                $users->each(
                    fn($user) => fputcsv($output, [$user->email, $user->name])
                );
            });
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This approach to CSV export is efficient, scalable, and simple to implement. By leveraging Laravelā€™s chunking and PHPā€™s native fputcsv, you ensure your application can handle even large datasets without performance issues.

laravel Article's
30 articles in total
Favicon
Serve a Laravel project on Web, Desktop and Mobile with Tauri
Favicon
Host Header Injection in Laravel: Risks and Prevention
Favicon
Laravel 11.30: A Leap Forward in Testing, Model IDs, and Authorization
Favicon
How to Effectively Manage Laravel Request Validation?
Favicon
[Boost]
Favicon
Building a Quick CSV Export Command in Laravel
Favicon
Deploy laravel application using vercel : Amazing
Favicon
How to Image Upload with CKeditor in Laravel 11 Tutorial
Favicon
How to Install and Use Trix Editor in Laravel 11
Favicon
Testing Temporary URLs in Laravel Storage
Favicon
API Vulnerabilities in Laravel: Identify & Secure Your Endpoints
Favicon
Enforcing Strong Passwords in Laravel
Favicon
Beyond MVC: Redefining Backend Development with DataForge
Favicon
From Product Manager to Independent Developer: A Six-Month Transformation Guide
Favicon
"PHP is deadāš°ļø" .. what's next? Is Laravel worth it? šŸ˜Ž
Favicon
LTS as a Business: How an Old Project Can Become the Foundation for a New Business Model
Favicon
How to Fix the "PHP Not Found" Error on macOS After Installing XAMPP
Favicon
Sending logs to Telegram. Module for Laravel
Favicon
Need someone to contribute in writing test code for my open source project
Favicon
6 Steps to Master PHPUnit Testing with Ease!
Favicon
How to Create a Reusable Laravel Admin Panel for Multiple Projects
Favicon
Day 6: Building APIs with Laravel Sanctum
Favicon
Fix Insufficient Logging & Monitoring in Laravel Easily
Favicon
šŸŽ‰ Simplify Laravel CRUD Operations with Ease! šŸš€
Favicon
Laravel IQ - Level 1 - Part 2
Favicon
Different ways to use where() in Laravel
Favicon
Laravel IQ - Level 1 - Part 1
Favicon
Leveraging Social Media to Attract Top PHP Developers
Favicon
Laravel Eloquent ORM in Bangla Part-3 (Models Retrieving)
Favicon
How to Build a Generic CRUD Controller in Laravel for Multiple Resources

Featured ones: