title: Use Laravel to Download table as CSV
body: <p>I am trying to export a database table using <code>Laravel</code> as a <code>csv</code> file. I would like the user to be able to select the <code>Export as CSV</code> button and download the table as a <code>csv</code> file. Currently I've gotten this code but It is not working:</p>
  
  <p>my button:</p>
  
  <pre><code>&lt;a href="/all-tweets-csv" class="btn btn-primary"&gt;Export as CSV&lt;/a&gt;
  </code></pre>
  
  <p>my route:</p>
  
  <pre><code>Route::get('/all-tweets-csv', function(){
  
      $table = Tweet::all();
      $filename = "tweets.csv";
      $handle = fopen($filename, 'w+');
      fputcsv($handle, array('tweet text', 'screen name', 'name', 'created at'));
  
      foreach($table as $row) {
          fputcsv($handle, array($row['tweet_text'], $row['screen_name'], $row['name'], $row['created_at']));
      }
  
      fclose($handle);
  
      $headers = array(
          'Content-Type' =&gt; 'text/csv',
      );
  
      return Response::download($handle, 'tweets.csv', $headers);
  });
  </code></pre>
  
  <p>It returns me this error:</p>
  
  <pre><code> The file "Resource id #154" does not exist
  </code></pre>
  
  <p>And I've gathered that it is because it is trying to download a file that does not exist. Is there an alternative way I can go about modifying my code in order to download as a <code>csv</code>. </p>