Trayer Trayer - 1 year ago 105
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 = [
'customer_id',
'count',
'year',
'month',
'day',
'hour'
];

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 ();
$this->info($logincount);


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

fclose($handle);

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

    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?

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