How To Export Data Into CSV File In Laravel 10

To export data as a CSV file in Laravel, you can use the built-in CSV functionality along with the file response. Here’s a step-by-step guide on How To Export Data Into CSV File In Laravel 10.

In a recent project, we need to export the rows from the database in laravel but I checked on google more than sites using the library if we generate csv using php function then why do we use any package? So lets see the below easy example for exporting CSV Data in laravel.

Step 1: Add Route

First, you need to add a route in your routes/web.php file just like below:

Route::get('/tasks', 'TaskController@exportCsv');

Step 2: In Blade File

Next, add an export button link in your blade file from where you want to export your data.

<span data-href="/tasks" id="export" class="btn btn-success btn-sm" onclick="exportTasks(event.target);">Export</span>

Step 3: In Js file

In this step add a export function in you js file to exporting data.

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

Step 4: In your Controller

In the last step, you need to add a function to export database columns in CSV in laravel application. Here we get all projects but you can modify the code which you want to export you can add columns and tasks.

public function exportCsv(Request $request)
{
   $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', 'Assign', '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['Assign']    = $task->assign->name;
                $row['Description']    = $task->description;
                $row['Start Date']  = $task->start_at;
                $row['Due Date']  = $task->end_at;

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

            fclose($file);
        };

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

Read: Import SQL file to Database using Command Line in Windows

I hope the above Exporting csv in laravel example helps you. If you have any questions please comment below.

7 thoughts on “How To Export Data Into CSV File In Laravel 10”

      • Dear Mike,

        No articles are copied in codingdriver. All the articles are self made, already done in the project. You can see all the articles in this blog. Copyright claim has also been made by us, soon you will not get the copied article on Google.

        Reply
  1. I want CRLF result for line break, with \n i get LF but with \r\n not working for get CRLF. Can anyone help with this?

    foreach ($datas as $line) {
    fputs($file, $line.”\n”);
    }

    Reply
    • I don’t know what you want to ask but here you can use this

      $handle = fopen(public_path(“test.csv”), ‘r’);
      while (($line = fgetcsv($handle, 4096)) !== false) {
      $dataString = implode(“, “, $line);
      $row = explode(‘;’, $dataString);
      yield$row;
      }

      If its not working please send your query with more details

      Reply

Leave a Comment