DeveloperBreeze

Eloquent Development Tutorials, Guides & Insights

Unlock 1+ expert-curated eloquent tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your eloquent skills on DeveloperBreeze.

Exporting Eloquent Data to CSV in Laravel

Tutorial October 24, 2024
php

use App\Models\User;
use Illuminate\Support\Facades\Response;

public function exportUsersToCsv()
{
    // Step 1: Retrieve user data
    $users = User::all();

    // Step 2: Define the CSV file path
    $filePath = storage_path('exports/users.csv');

    // Step 3: Open the CSV file for writing
    $file = fopen($filePath, 'w');

    // Step 4: Write the CSV header
    $header = ['Name', 'Email', 'Registration Date'];
    fputcsv($file, $header);

    // Step 5: Write data rows
    foreach ($users as $user) {
        $rowData = [
            $user->name,
            $user->email,
            $user->created_at->format('Y-m-d'), // Format the date to Year-Month-Day
        ];
        fputcsv($file, $rowData);
    }

    // Step 6: Close the file
    fclose($file);

    // Step 7: Return the CSV file as a download response
    return response()->download($filePath)->deleteFileAfterSend(true);
}

Instead of saving the CSV to a permanent location, you can use a temporary file. This is useful if you don't want to keep the exported files on the server.