Laravel-excel: Problem with method prepareRows.

Created on 20 Jan 2021  路  7Comments  路  Source: Maatwebsite/Laravel-Excel

ErrorException: array_map(): Expected parameter 2 to be an array, object given

My code

` class CasesExports implements FromQuery, WithMapping, WithHeadings
{
use Exportable;
private $user;
private $paramsQuery;
public function __construct($user, $paramsQuery)
{
$this->user = $user;
$this->paramsQuery = $paramsQuery;
}
public function query()
{
$children = Child::where('tenant_id', '=', $this->user->tenant_id);
$children->where("name", "like", "%" . $this->paramsQuery['name'] . "%");
return $children;
}

public function map($children): array
{
    return [
        $children->name,
        $children->mother_name,
        $children->father_name
    ];
}

public function prepareRows($children): array
{
    return [
        $children->name . 'test',
        $children->mother_name,
        $children->father_name
    ];
}

public function headings(): array
{
    return [
        '#',
        'User',
        'Date',
    ];
}

}
`

Most helpful comment

I got a same error when I tried the example code on doc.
Because $rows passed to prepareRows() is a collection, it cannot go through array_map().
Instead of using array_map(), I tried this and worked fine.

public function prepareRows($rows)
{
    return $rows->transform($function($user) {
        $user->name .= ' (prepared)';
        return $user;
    });
}

All 7 comments

Hi @rafaelecs1 the prepareRows should return iterable array with items. please see doc Prepare rows

I tried this, but got ErrorException: array_map(): Expected parameter 2 to be an array, object given.

prepareRows receives all rows, not one like map. You have to loop over those rows yourself (like array_map example in the docs), you can't return a single row.

Please next time fill in the mandatory issue template, it's there for a reason.

I got a same error when I tried the example code on doc.
Because $rows passed to prepareRows() is a collection, it cannot go through array_map().
Instead of using array_map(), I tried this and worked fine.

public function prepareRows($rows)
{
    return $rows->transform($function($user) {
        $user->name .= ' (prepared)';
        return $user;
    });
}

If someone could PR the docs, that would be great

@derickhino Thx bro. Works fine here using your code.

I had the same problem, used @hhino-dev suggestion and it worked. created a PR for the docs https://github.com/Maatwebsite/laravel-excel-docs/pull/145

Was this page helpful?
0 / 5 - 0 ratings