Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export whole table to CSV using laravel

I am new to laravel and having a tough time figuring out a way to export one table to csv. I have tried the following code in the controller class, but it gives me an error:

    public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row);
    }
    fclose($file);
    return Redirect::to('consolidated');
}

Model Class for Cpmreport:

    class Cpmreport extends Eloquent
    {
      public static $table='cpm_report';
    }

The error :

    Message:

    fputcsv() expects parameter 2 to be array, object given

    Location:

    C:\xampp\htdocs\cpm_report\application\controllers\cpmreports.php on line 195

Any help would be appreciated.

like image 430
Anuj Avatar asked Apr 16 '13 11:04

Anuj


People also ask

How do I export a csv file in laravel?

Export CSV file in laravel is the most common function and many times we are using this function using plugins or readymade functions. Also in this example, we use fopen() and fputcsv() function. The fputcsv() function formats a line as CSV and writes it to an open file. The fopen() function opens a file or URL.


2 Answers

Easy way

Route::get('/csv', function() {
  $table = Cpmreport::all();
  $output='';
  foreach ($table as $row) {
      $output.=  implode(",",$row->toArray());
  }
  $headers = array(
      'Content-Type' => 'text/csv',
      'Content-Disposition' => 'attachment; filename="ExportFileName.csv"',
  );

  return Response::make(rtrim($output, "\n"), 200, $headers);
});
like image 165
Dinesh Rabara Avatar answered Oct 27 '22 09:10

Dinesh Rabara


fputcsv($file, $table); should be fputcsv($file, $row), shouldn't it?

And convert the object to an array using Eloquent's to_array()method: http://laravel.com/docs/database/eloquent#to-array

public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row->to_array());
    }
    fclose($file);
    return Redirect::to('consolidated');
}
like image 40
sqwk Avatar answered Oct 27 '22 10:10

sqwk