Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel download query results as CSV [duplicate]

I am trying to download a query as CSV and face currently two issues:

  1. A file is created in the public folder. It contains the query data. That is really bad, because it should not exist in the public folder.

  2. A file is also downloaded, but the downloaded file is empty.

Here is the function:

public function get_chatmessages(Request $data) {

    try {  
        if ($data->chat_to_user) {              
            $result = DB::connection('mysql_live')->table('user_chatmessages')
                ->where(function($query) use($data) {
                    $query->where('from_user', $data->chat_from_user)->where('to_user', $data->chat_to_user);
                })->orWhere(function($query) use($data) {
                    $query->where('to_user', $data->chat_from_user)->where('from_user', $data->chat_to_user);
                })->orderBy('date_added', 'asc')->get();
        } else {
            $result = DB::connection('mysql_live')->table('user_chatmessages')
            ->where('from_user', $data->chat_from_user)
            ->orWhere('to_user', $data->chat_from_user)
            ->orderBy('date_added', 'asc')
            ->get();
        }

        //\Log::info($data);
        //\Log::info($result);

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

        $columns = array('from_user', 'to_user', 'message', 'date_added');
        $callback = function() use ($result, $columns) {
            $file = fopen('output_chat.csv', 'w');
            fputcsv($file, $columns);

            foreach($result as $res) {
                fputcsv($file, array($res->from_user, $res->to_user, $res->message, $res->date_added));
            }
            fclose($file);
        };

        //return response()->download('output_chat.csv', 'DL_output_chat.csv', $headers);
        //return response()->make($callback, 200, $headers);
        return response()->stream($callback, 200, $headers);  

    } catch (\Exception $e) {  
        return redirect('home')->with('error', $e->getMessage());  
    } 

    return redirect('home')->with('error', 'Etwas ist schief gelaufen');  
}
like image 950
Roman Avatar asked Sep 08 '25 10:09

Roman


1 Answers

I made little changes in your snippet regarding php://output

$headers = [
    "Content-type"        => "text/csv",
    "Content-Disposition" => "attachment; filename=output_chat.csv", // <- name of file
    "Pragma"              => "no-cache",
    "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
    "Expires"             => "0",
];
$columns  = ['from_user', 'to_user', 'message', 'date_added'];
$callback = function () use ($result, $columns) {
    $file = fopen('php://output', 'w'); //<-here. name of file is written in headers
    fputcsv($file, $columns);
    foreach ($result as $res) {
        fputcsv($file, [$res->from_user, $res->to_user, $res->message, $res->date_added]);
    }
    fclose($file);
};
like image 169
Rahul Avatar answered Sep 09 '25 23:09

Rahul