harunB10
harunB10

Reputation: 5207

Export content to CSV file

I am using "league/csv": "^8.2"package for CSV export/import and I try this code to export content to CSV file:

public function exportCSV($id)
{
    $users= User::find($id);

    $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());
    $csv->insertOne(\Schema::getColumnListing('users'));
    foreach ($users as $user) {
        $csv->insertOne($user->toArray());
    }
    $csv->output('users.csv');
}

But I'm getting error FatalErrorException: Call to a member function toArray() on boolean.

When I do dd($users) I get the Collection, not the boolean value. Any help?

EDIT

@Alexey Mezenin's answer helped me. But is there a way to insert new column using this package? I've tried this:

$rows     = [
        [1, 2, 3],
        ['foo', 'bar', 'baz'],
        'test',
    ];
$csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());
$csv->insertAll($rows);
$csv->output('users.csv');

But it inserts data into new row every time. Like:

'1,2,3
foo, bar,baz
test

I want to have a new column for each array...

EDIT 2

I solved it using:

$csv->setDelimiter(';');

Upvotes: 0

Views: 776

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163838

When you're using find() you're getting an instance of a User model, not a collection. Use get instead:

$users = User::get();

If you want to get just one use by ID, remove the loop:

$user = User::find($id);
....
$csv->insertOne($user->toArray());

Upvotes: 2

Related Questions