title: Laravel download query results as CSV
body: <p>I am trying to download a query as CSV and face currently two issues:</p>
  
  <ol>
  <li><p>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.</p></li>
  <li><p>A file is also downloaded, but the downloaded file is empty.</p></li>
  </ol>
  
  <p>Here is the function:</p>
  
  <pre><code>public function get_chatmessages(Request $data) {
  
      try {  
          if ($data-&gt;chat_to_user) {              
              $result = DB::connection('mysql_live')-&gt;table('user_chatmessages')
                  -&gt;where(function($query) use($data) {
                      $query-&gt;where('from_user', $data-&gt;chat_from_user)-&gt;where('to_user', $data-&gt;chat_to_user);
                  })-&gt;orWhere(function($query) use($data) {
                      $query-&gt;where('to_user', $data-&gt;chat_from_user)-&gt;where('from_user', $data-&gt;chat_to_user);
                  })-&gt;orderBy('date_added', 'asc')-&gt;get();
          } else {
              $result = DB::connection('mysql_live')-&gt;table('user_chatmessages')
              -&gt;where('from_user', $data-&gt;chat_from_user)
              -&gt;orWhere('to_user', $data-&gt;chat_from_user)
              -&gt;orderBy('date_added', 'asc')
              -&gt;get();
          }
  
          //\Log::info($data);
          //\Log::info($result);
  
          $headers = array(
              "Content-type" =&gt; "text/csv",
              "Content-Disposition" =&gt; "attachment; filename=file.csv",
              "Pragma" =&gt; "no-cache",
              "Cache-Control" =&gt; "must-revalidate, post-check=0, pre-check=0",
              "Expires" =&gt; "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-&gt;from_user, $res-&gt;to_user, $res-&gt;message, $res-&gt;date_added));
              }
              fclose($file);
          };
  
          //return response()-&gt;download('output_chat.csv', 'DL_output_chat.csv', $headers);
          //return response()-&gt;make($callback, 200, $headers);
          return response()-&gt;stream($callback, 200, $headers);  
  
      } catch (\Exception $e) {  
          return redirect('home')-&gt;with('error', $e-&gt;getMessage());  
      } 
  
      return redirect('home')-&gt;with('error', 'Etwas ist schief gelaufen');  
  }
  </code></pre>