Laravel生成含商品与公司信息PDF报错:Undefined property: stdClass::$items
解决Laravel中PDF生成时关联属性未定义的错误
嘿,我来帮你揪出问题根源并搞定这个报错!你遇到的Undefined property: stdClass::$items错误,核心问题出在控制器的查询方式上,咱们一步步拆解:
错误根源
你在控制器里用DB::table("invoices")->get()获取发票数据,这种方式返回的是stdClass类型的普通对象集合,而非你定义的Invoice Eloquent模型实例。
普通对象不具备你在Invoice模型里定义的company和items关联关系,所以当你在视图里调用$invoice->company或者$invoice->items时,PHP就会报错说找不到这些属性。
修复步骤
1. 修改控制器的查询逻辑
把DB查询换成Eloquent模型查询,同时预加载关联关系(还能避免N+1查询的性能问题):
public function pdfviewInvoice(Request $request) { // 用Invoice模型查询,同时预加载company和items关联数据 $invoices = Invoice::with('company', 'items')->get(); view()->share('invoices', $invoices); if ($request->has('download')) { // 不需要单独查询Company和Item,关联数据已经通过invoices带过来了 $pdf = PDF::loadView('pdf.pdfviewInvoice', compact('invoices')); return $pdf->download('pdfviewInvoice.pdf'); } return view('pdfviewInvoice'); }
2. 视图的标签修正(避免渲染异常)
你的嵌套表格标签有小问题,补充完整<thead>和<tbody>,同时确保标签闭合:
@foreach($invoices as $key => $invoice) <tr> <td>{{ ++$key }}</td> <td>{{ $invoice->number }}</td> <td>{{ $invoice->status }}</td> <td>{{ $invoice->place_issue }}</td> <td>{{ $invoice->date_issue }}</td> <td>{{ $invoice->date_payment }}</td> <td>{{ $invoice->company->name }}</td> <td> <table class="table text-center"> <thead> <tr> <td class="text-center">Item</td> <td class="text-center">Unit</td> <td class="text-center">Price</td> <td class="text-center">VAT</td> <td class="text-center">Quantity</td> </tr> </thead> <tbody> @foreach($invoice->items as $item) <tr> <td>{{ $item->name }}</td> <td>{{ $item->unit }}</td> <td>{{ $item->price_net }}</td> <td>{{ $item->vat->value."%"}}</td> <td>{{ $item->pivot->quantity }}</td> </tr> @endforeach </tbody> </table> </td> </tr> @endforeach
为什么这样改?
Invoice::with('company', 'items')->get()返回的是Invoice模型实例集合,每个实例都能调用你在模型里定义的关联方法。with()方法是预加载关联,能一次性查出所有发票对应的公司和商品数据,比循环内再查关联性能好很多。- 下载PDF时不需要单独查询
Company::all()和Item::all(),这些数据已经通过发票的关联关系获取到了。
内容的提问来源于stack exchange,提问作者Magda
相关产品推荐
相关产品推荐

