support@codebucket.net

How to Export large data into CSV format in Laravel

How to Export large data into CSV format in Laravel

K. M. Shawkat Zamil | September 25, 2022

Hello Developers,

I will show you how to export extensive data in CSV format directly in this demonstration. We have faced these errors when handling a large amount of data. Follow those steps to complete the process:

 

First Step: Creating the route

 

On the web.php we have to create a route.

 

 route/web.php

Route::post('/csv_download', [SampleController::class, 'csv_download'])->name('report.csv_download');

 

Second Step: Add a button and javascript in the view file

 

Now we have to add the download button in the view file.

 

resources/views/sample.php

<div class="col-md-4 col-sm-4  col-xs-4">
    <div class="form-group row">
        <a class="btn btn-primary submit text-white" id="DownloadCSV">Download CSV</a>
        &nbsp;&nbsp;&nbsp;
        <div id="loaderDivLoad"></div>
        &nbsp;&nbsp;&nbsp;
        <a href="" class="btn btn-primary submit" id="SaveFile" style="display: none;">File</a>
    </div>
</div>

 

Now we have to add the javascript to the view file.

 

$('#DownloadCSV').click(function() {
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    var dataString = '_token=' + '{{ csrf_token() }}';
    $.ajax({
        type: 'POST',
        url: "{{ route('report.csv_download') }}",
        data: dataString,
        cache: false,
        beforeSend: function() {
            $("#loaderDivLoad").html(
                '<img src="{{ asset('assets/images/ajax-loader.gif') }}" alt="Wait" />'
            );
        },
        success: function(html) {
            $("#loaderDivLoad").html('');
            //console.log(html);
            $("#SaveFile").show();
            $('#SaveFile').attr('href', html);
            $('#SaveFile').attr('name', html);
        }
    });
});

$('#SaveFile').click(function() {
    $('#SaveFile').hide();
});

 

Put the below image in the assets/images/ folder and create a folder named csv_file in the storage directory

 

Third Step: Add the function in the controller

 

Add the below function to the controller

 

app/Http/Controllers/SampleController

public function csv_download(Request $request)
    {
        $user_id = Auth::user()->UserID;

        $file_name = $user_id . '_' . str_replace(' ', "_", 'csv_report') . date("Y_m_d_H_i_s", strtotime('now')) . '.csv';
        $output = fopen(storage_path('app/public/csv_file/') . $file_name, 'w');
        //dd($output);
        $header = array('Column 1', 'Column 2', 'Column 3');

        $bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
        fputs($output, $bom);
        fputcsv($output, $header);

         /**
          * 
          * Put the TableName in the query
          * Think That this table has 1000000 rows
          */

        $data = DB::select("Select * from TableName");
        $data = json_decode(json_encode($data), true);
        foreach ($data as $row) {
            fputcsv($output, $row);
        }
        fclose($output);
        echo asset('storage/csv_file/') . '/' . $file_name;

    }

 

That's it. If you press the download button then the large data is exported in a CSV file in Laravel Project.

Hope this might help you in the development journey.

 

Read More: Remove Public Path From URL in Laravel Without htaccess

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.