导出Excel时出现此错误试图获取非对象的属性“ id”

时间:2018-06-25 11:12:44

标签: laravel laravel-excel

我正在使用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问题

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

看来,问题出在 InvoicesExport 类之外。

为什么不更改退货类型?

而不是返回

 if(level == 3){
          this.game = previous_game; // i define previous_game = this.game; when level was 2. But nothing changed.  
           this.handler = handler; // same as up;
           this.HUD = HUD;// heads of display but nothing was changed except i saw a black screen i thing because the background is black(background is black) please help i dont see any answers of this.
} 

这样做:

return $assets_array;