formatToCsv($results); // Send the CSV file to the client $filename = "export.csv"; return response($csvOutput, 200) ->header('Content-Type', 'text/csv') ->header('Content-Disposition', "attachment; filename=$filename"); } protected function formatToCsv($data) { $handle = fopen('php://temp', 'w'); // Add headers for CSV (if needed) fputcsv($handle, [ 'ID', 'Title', 'Lead Time', 'Short Description', 'Learning Goals', 'Review', 'Certification', 'Extra Information', 'Target Audience', 'Quality Standards', 'Contract Agreements', 'Cover', 'Thumb', 'Titles and Credits' ]); foreach ($data as $row) { fputcsv($handle, [ $row->id, strip_tags($row->title), strip_tags($row->lead_time), strip_tags($row->short_description), strip_tags($row->learning_goals), strip_tags($row->review), strip_tags($row->certification), strip_tags($row->extra_information), strip_tags($row->target_audience), strip_tags($row->quality_standards), strip_tags($row->contract_agreements), $row->cover, $row->thumb, $row->titles_and_credits ]); } rewind($handle); $contents = stream_get_contents($handle); fclose($handle); return $contents; } }