导出 Excel 出现此错误尝试获取非对象的 属性 'id'

Exporting Excel getting this error Trying to get property 'id' of non-object

我正在使用 Maatwebsite Laravel Excel 包 3.0。 这是我的 InvoicesExport.php

    class InvoicesExport implements FromCollection
{
    public function collection()
    {
        $company_id = Auth::user()->company_id;
         $assets = Asset::where('id', $company_id)->get()->toArray();    
         $assets_array = array();
        if(!$assets->isEmpty()){
         foreach($assets as $asset){
             $assets_array[] = array(
             'Asset ID' => $asset->id,
             'Asset Name' => $asset->name,
             'Description' => $asset->description,
             'Serial Number' => $asset->serialno,
             'External ID' => $asset->external_id,
             'Location' => $asset->location,
             'Expiry Date' => $asset->expiry_date,
             'Owner' => $asset->owner,
             'Status' => $asset->status,
             'Updated at' => $asset->updated_at
             );
            }
        }
        //dd($assets_array); 
        return $assets_array;
    }
}

而且我不断收到此错误

Trying to get property 'id' of non-object

这是我在控制器中的功能

public function excel() 
    {    
          return Excel::download(new InvoicesExport, 'invoices.xlsx');
    }

我的代码现在看起来像这样,但我不断收到此错误。

Call to a member function each() on array

当我使用 dd($assets_array) 时,我得到了数据库中的那两个项目,所以我想这可能是我的 RETURN[=28= 中的问题]

您将集合转换为数组并尝试将其作为对象访问 只需删除 toArray

    $assets = Asset::where('id', $company_id)->get();

看来,问题出在 InvoicesExport Class.

之外

你为什么不更改 return 的类型?

而不是 returning

return $assets_array;

这样做:

return collect($assets_array);