Trayer Trayer - 1 year ago 115
PHP Question

Use Laravel php artisan command to export database table as CSV

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.

This is my table:

public function up() {
Schema::create ( 'logincount', function (Blueprint $table) {
$table->bigIncrements ( 'id' );
// $table->string('queue');
$table->integer( 'customer_id' );
$table->integer( 'count' );
$table->integer( 'year' );
$table->integer( 'month' );
$table->integer( 'day' );
$table->integer ( 'hour' );
$table->timestamps ();
} );

This is my model:

class Logincount extends Model {
use BelongsToTenant;
protected $table = 'logincount';
protected $primaryKey = 'customer_id';
protected $fillable = [

public function returncount(){
return DB::table ( 'logincount' )->select ( 'count', 'year', 'month' , 'day' , 'hour')->get ();

And here is my Artisan Command:

public function handle() {
$logincount = $this->logincount->all ();

$table = logincount::all();
$filename = "logins.csv";

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

foreach($table as $row) {
fputcsv($handle, array($row['customer_id'], $row['count'], $row['year'], $row['month'], $row['day'], $row['hour']));


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

Answer Source

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']"));


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

creates file logins.csv in the project root directory


btw what is purpose of $headers array ?

CLI shows me only the data from the database

maybe you have dd() somewhere?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download