Tuesday, 28 May 2024

Laravel Export data to csv

 use Illuminate\Http\Response;


// Define a function to export data to CSV

function exportToCSV($exportData, $columns)

{

    $filename = "ReportsForm.csv";


    // Set HTTP headers

    $headers = [

        'Content-type' => 'text/csv',

        'Content-Disposition' => "attachment; filename=$filename",

        'Pragma' => 'no-cache',

        'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',

        'Expires' => '0',

    ];


    // Create a callback function to stream CSV data

    $callback = function () use ($exportData, $columns) {

        $file = fopen('php://output', 'w');

        fputcsv($file, $columns);

        $i = 1;

        foreach ($exportData as $item) {

            $currentData = [

                $i++,

                $item->name,

                $item->email,

                $item->company,

                $item->country,

                $item->hear_from,

                $item->is_subscribed == 0 ? "YES" : "NO",

                $item->created_at,

            ];

            fputcsv($file, $currentData);

        }

        fclose($file);

    };


    // Return a streamed response

    return response()->stream($callback, Response::HTTP_OK, $headers);

}


// Controller method to handle export

public function exportData($id = null)

{

    try {

        if (empty($id)) {

            $exportData = ReportForm::all();

        } else {

            $exportData = ReportForm::whereIn('id', $id)->get();

        }


        // Define columns for CSV

        $columns = ["Index", "Name", "Email", "Company", "Country", "Hear From", "Subscribed", "Date"];


        // Export data to CSV

        return exportToCSV($exportData, $columns);

    } catch (\Exception $e) {

        // Handle exceptions

        return response()->json(['error' => 'Failed to export data.'], Response::HTTP_INTERNAL_SERVER_ERROR);

    }

}


No comments:

Post a Comment

Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...