1

I'm writing a artisan command to export the table from my database as a csv file. But when im running the command, the CLI shows me only the data from the database and don't create a CSV File.

3
  • Any errors? Are you sure that user that runs command has permissions to do this? Commented Jul 26, 2017 at 13:38
  • @skido no , no errors. and yes the user has the permission. Commented Jul 26, 2017 at 14:03
  • have you tried making an artisan command that just writes some random data? Or in other words, try testing all individual components Commented Jul 26, 2017 at 14:07

2 Answers 2

2

this works fine in my laravel 5.4 project

public function handle()
{
    $filename = "logins.csv";

    $handle = fopen($filename, 'w');
    fputcsv($handle, array('customer_id', 'count', 'year', 'month', 'day', 'hour'));

    fputcsv($handle, array("row['customer_id']", "row['count']", "row['year']", "row['month']", "row['day']", "row['hour']"));

    fclose($handle);

    $headers = array(
        'Content-Type' => 'text/csv',
    );
}

creates file logins.csv in the project root directory

customer_id,count,year,month,day,hour
row['customer_id'],row['count'],row['year'],row['month'],row['day'],row['hour']

btw what is purpose of $headers array ?

CLI shows me only the data from the database

maybe you have dd() somewhere?

Sign up to request clarification or add additional context in comments.

Comments

1

You could try this library: https://github.com/box/spout.

Allows you to create CSV, XLSX, ODS files easily like this:

use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;

$writer = WriterFactory::create(Type::XLSX); // for XLSX files
//$writer = WriterFactory::create(Type::CSV); // for CSV files
//$writer = WriterFactory::create(Type::ODS); // for ODS files

$writer->openToFile($filePath); // write data to a file or to a PHP stream
//$writer->openToBrowser($fileName); // stream data directly to the browser

$writer->addRow($singleRow); // add a row at a time
$writer->addRows($multipleRows); // add multiple rows at a time

$writer->close();

You will just pass the rows as arrays and that's it.

You can find the documentation here: http://opensource.box.com/spout/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.