Export whole table to CSV using laravel
Asked Answered
C

4

6

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.

Commissure answered 16/4, 2013 at 11:39 Comment(1)
Possible duplicate of Use Laravel to Download table as CSV - see also meta.stackexchange.com/a/147651/321521Jimmie
I
11

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->toArray());
    }
    fclose($file);
    return Redirect::to('consolidated');
}
Intellect answered 16/4, 2013 at 12:48 Comment(2)
yes, sorry that was a typo, but it is still not working with $rowCommissure
Have a look at Eloquent's to_array() method. laravel.com/docs/database/eloquent#to-arrayIntellect
L
22

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);
});
Lamb answered 7/2, 2014 at 10:6 Comment(5)
$output= inside foreach gets the last valueRespire
Note that this requires an eloquent collection query to get the $table. A DB::('tablename') query will need to be run as an eloquent query and a model created (if it's not been already)Berry
doesn't create newlinesIngeingeberg
you can add "\n" at every end of the lineLamb
Note this doesn't escape any commas, quotes, or the like. Best to use fputcsv as demonstrated in this answer.Jimmie
I
11

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->toArray());
    }
    fclose($file);
    return Redirect::to('consolidated');
}
Intellect answered 16/4, 2013 at 12:48 Comment(2)
yes, sorry that was a typo, but it is still not working with $rowCommissure
Have a look at Eloquent's to_array() method. laravel.com/docs/database/eloquent#to-arrayIntellect
M
3

Select query of MySQL data.

$data = \DB::connection('mysql')->select($select);

Call following function:

query_to_csv($data, 'data.csv');

function data_to_csv($data, $filename)
    {
        $fp = fopen($filename, 'w');
        foreach ($data as $row) {
            fputcsv($fp, $row);
        }

        fclose($fp);
    }

0.1 Million records takes 1 second to create.

Madaih answered 15/4, 2015 at 9:5 Comment(3)
I've 5000 records but its taking around 3-4 minutes using Laravel 5Brittbritta
It doesn't take that much time. Might be issue with file permissions? @tiGerMadaih
I'm directly downloading the file, didn't understand about file permissions.Brittbritta
S
-1

this is better and simple.

$file_name = "abc";
$postStudent = Input::all();
$ck = DB::table('loan_tags')->select('LAN')->where('liabilitiesId', $postStudent['id'])->get();
$i = 0;
foreach ($ck as $row) { 

              $apps[$i]['LAN'] = $row->LAN;
            $apps[$i]['Account_number'] =   $postStudent['account_number'];
            $apps[$i]['Bank_Name'] =  $postStudent['bank_name'];
            $i++;
}

ob_end_clean();
ob_start();
Excel::create($file_name, function($excel) use($apps){
        $excel->sheet('Sheetname', function($sheet) use($apps){

           $sheet->row(1, array(
                 'LAN', 'Account number' , 'Bank Name'
            ));
            $k = 2;
             foreach ($apps as $deta) {
                 $sheet->row($k, array($deta['LAN'],   $deta['Account_number'], $deta['Bank_Name']
                ));
                $k++;
             }
        });
    })->download('xlsx');
Stylobate answered 17/1, 2017 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.