DEV Community

vidvatek
vidvatek

Posted on • Originally published at vidvatek.com

How To Export CSV File In Laravel 10 Example

In the modern world of web development, data is the lifeblood of many applications. As a Laravel developer, I often need to provide users with a way to export data from my Laravel applications for further analysis, reporting, or sharing with other systems. That's where the Comma-Separated Values (CSV) format comes in handy.

In this article, I will delve into the process of exporting CSV files in Laravel 10, a powerful PHP framework known for its simplicity and elegance.

Together, we will explore the necessary steps to export data from our Laravel application to a CSV file, giving us the ability to effortlessly generate and deliver structured data in a universally accepted format.

Throughout this tutorial, I will cover essential concepts and practical examples to help us grasp the underlying mechanisms of CSV exportation in Laravel.

Whether you are a seasoned Laravel developer like me or just starting your journey with the framework, this guide will equip you with the knowledge and skills to implement CSV exporting functionality efficiently.

let's dive in together and learn how to export CSV files from our Laravel application step by step.

Step 1: Setup Laravel 10

Ensure you have a Laravel 10 project set up and ready for export CSV files. If you haven't created a Laravel project yet, you can use the following command to create one.

composer create-project --prefer-dist laravel/laravel export_csv_file_example
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a route for CSV export

Next, let's define a route in Laravel to handle the CSV export functionality. Open the routes/web.php file and add the following code

use App\Http\Controllers\CSVExportController;

Route::get('/export-csv', [CSVExportController::class, 'export'])->name('export.csv');
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a CSVExportController

Now, let's create a new controller to handle the CSV export logic. Run the following command in your terminal to generate the controller.

php artisan make:controller CSVExportController
Open the newly created CSVExportController.php file.

app/Http/Controllers directory and replace its content with the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Models\Task;

class CSVExportController extends Controller
{
    public function export()
    {
        $fileName = 'tasks.csv';
        $tasks = Task::all();

        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );

        $columns = array('Title', 'Description', 'Start Date', 'Due Date');

        $callback = function() use($tasks, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($tasks as $task) {
                $row['Title']  = $task->title;
                $row['Description']    = $task->description;
                $row['Start Date']  = $task->start_at;
                $row['Due Date']  = $task->end_at;

                fputcsv($file, array($row['Title'], $row['Description'], $row['Start Date'], $row['Due Date']));
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);

    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Blade File

Add an export button link in your blade file from where you want to export your data.

<span data-href="/export-csv" id="export" class="btn btn-success btn-sm" onclick ="exportTasks(event.target);">Export</span>
Now, add the below script after the body tag.

<script>
   function exportTasks(_this) {
      let _url = $(_this).data('href');
      window.location.href = _url;
   }
</script>
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Laravel 10 Application
Now, start your Laravel development server by running the command.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Step 5: Conclusion

In this comprehensive guide, we explored the process of exporting CSV files in Laravel 10.

By following the step-by-step example, we learned how to generate CSV files from our Laravel application and provide users with the ability to download structured data in a universally accepted format.

Top comments (0)