![](/img/trans.png)
[英]Call to a member function update() on null Laravel function
[英]Laravel call to member function on null
我花了最后一個小時谷歌搜索和閱讀有關此問題的堆棧文章,但無法解決此問題。 我附加了try catch和if語句,但仍然call to member function on null error
得到call to member function on null error
的call to member function on null error
。 這是我的代碼
try{
$user = Auth::user();
if(null !== ($user->wasStripePlan())){
$data['allSubscriptions'] = (Auth::user()->wasStripePlan()) ? Auth::user()->subscriptions : [];
}
}catch (\PDOException $e){
$data['allSubscriptions'] = false;
}
關於解決方案有什么想法嗎?
我認為您正在嘗試不登錄而訪問Auth :: user()。如果您未登錄並且不需要使用try and catch塊,它將返回null。
該錯誤是不言自明的。
在null上調用成員函數
如果查看內部,則try塊成員函數調用位於Auth :: user()之后的if條件中,由於某些原因(例如未登錄),該函數可能返回null。
if(null !== ($user->wasStripePlan()))
根據錯誤, $ user變量為空。 嘗試找出為什么Auth :: user()返回null的原因。
我認為您過分考慮了這一點。 簡單的if / else語句可以處理時,無需執行try / catch。
if(isset(Auth::user()){
$data['allSubscriptions'] = $data['allSubscriptions'] = (Auth::user()->wasStripePlan()) ? Auth::user()->subscriptions : [];
}else{
$data['allSbuscriptions'] = false;
}
由於您檢查用戶是否使用isset登錄,因此不會引發任何錯誤,也無需嘗試捕獲一個錯誤。 另外,除非您知道會引發哪種錯誤,否則我只會在catch塊上使用基類Exception。 因為除非Exception類型匹配,否則它將無法解決捕獲問題。 由於所有類型都繼承自Exception,因此您將捕獲出現的第一個類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.