Published on October 24, 2024By DeveloperBreeze

Tutorial: Exporting Eloquent Data to CSV in Laravel

In this tutorial, we will learn how to export data from a Laravel Eloquent model to a CSV file and make it available for download. This is a useful feature for exporting reports, logs, or any other kind of data.

We'll use an example where a User model stores user information such as name, email, and registration date, and we want to export this data to a CSV file.

Step 1: Set Up Your Laravel Model

For this example, let's assume you have a User model that represents the users in your application. If you don't have this model, you can create it by running:

php artisan make:model User

Ensure that your database has a table for users with fields such as name, email, and created_at (the registration date).

Step 2: Retrieve Data From the Database

In this step, we’ll retrieve all the user data from the database using Eloquent’s User::all() method. You can customize this query based on your requirements (for instance, retrieving only active users or users within a specific date range).

use App\Models\User;

$data = User::all();

Step 3: Define the CSV File Path

We will use the storage_path() helper to define the location where the CSV file will be temporarily stored. This example saves the file in the storage/exports directory.

$filePath = storage_path('exports/users.csv');

Step 4: Open a File for Writing

We use PHP’s fopen() function to open a new file in write mode (w). This file will be used to store the data in CSV format.

$file = fopen($filePath, 'w');

Step 5: Write the CSV Header

Next, we write the header of the CSV file. This will define the columns of the CSV. In our case, we will include name, email, and registration_date.

$header = ['Name', 'Email', 'Registration Date'];
fputcsv($file, $header);

Step 6: Write Data Rows

Now, we loop through the retrieved user data and write each user’s details to the CSV file. Each row in the CSV will contain the user’s name, email, and registration date.

foreach ($data as $user) {
    $rowData = [
        $user->name,
        $user->email,
        $user->created_at->format('Y-m-d'), // Format date as needed
    ];
    fputcsv($file, $rowData);
}

Step 7: Close the CSV File

Once all the data has been written to the file, we need to close it using fclose().

fclose($file);

Step 8: Return the File as a Downloadable Response

Finally, we return the CSV file to the user as a downloadable response using Laravel’s Response::download() method. The deleteFileAfterSend(true) function ensures that the file is deleted after it is sent to the user.

return response()->download($filePath)->deleteFileAfterSend(true);

Full Example Code

Here’s the complete example of how to export user data to a CSV file in a Laravel controller method:

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);
}

Step 9: Using Temporary Files for CSV Export (Optional)

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.

$tempFilePath = tempnam(sys_get_temp_dir(), 'users');
$file = fopen($tempFilePath, 'w');

// Write the CSV header and rows as described above...

fclose($file);

return response()->download($tempFilePath, 'users.csv')->deleteFileAfterSend(true);

Conclusion

This tutorial demonstrates how to export data from a Laravel Eloquent model into a CSV file and return it as a downloadable response. Whether you’re exporting user data, product reports, or any other dataset, this method is simple and scalable. With a few modifications, you can tailor this solution to fit the needs of your specific Laravel application.

Comments

Please log in to leave a comment.

Continue Reading:

Upload and Store File in Laravel

Published on January 26, 2024

php

Create Event and Listener in Laravel

Published on January 26, 2024

bash

Querying Data from Database Table in Laravel

Published on January 26, 2024

php

Laravel CSRF-Protected Form

Published on January 26, 2024

html

Create Resource Controller in Laravel

Published on January 26, 2024

bash

Laravel Validation Rules for User Registration

Published on January 26, 2024

php

Blade View in Laravel Extending Layout

Published on January 26, 2024

html