Laravel 8.83.27调用refreshPrice()报空对象错误,求修复方案
解决Laravel中Call to a member function refreshPrice() on null错误
问题原因
你的代码逻辑顺序有误:在调用$invoice->refreshPrice()方法之后才判断$invoice是否为空。用户完成线下支付后,对应发票会被标记为已支付状态,此时$customer->invoices()->unpaid()->where('uid', '=', $request->invoice_uid)->first()查询不到任何记录,$invoice变量变为null,直接调用方法就会触发这个错误。
修复方法
调整代码执行顺序,先判断$invoice是否存在,不存在则直接跳转;确认存在后再调用refreshPrice()方法。修改后的代码如下:
public function payment(Request $request) { // Get current customer $customer = $request->user()->customer; // get unpaid invoice $invoice = $customer->invoices()->unpaid()->where('uid', '=', $request->invoice_uid)->first(); // no unpaid invoice found if (!$invoice) { // throw new \Exception('Can not find unpaid invoice with id:' . $request->invoice_uid); // just redirect to index return redirect()->action('SubscriptionController@index'); } // always update invoice price from plan $invoice->refreshPrice(); // nếu đang có pending transaction thì luôn show màn hình pending if ($invoice->getPendingTransaction()) { return view('subscription.pending', [ 'invoice' => $invoice, ]); } // 后续业务代码... }
额外说明
错误仅出现一次的原因是:第一次触发错误跳转后,前端页面不再持有已支付发票的invoice_uid,后续操作不会再查询这个已失效的发票ID,因此用户之后能正常使用。调整代码顺序后,就能避免这次错误提示,提升用户体验。
内容的提问来源于stack exchange,提问作者ThankYouCamOnGraciasXieXie
相关产品推荐
相关产品推荐

