嘗試在 Laravel 9 中讀取 null 屬性'id”
P粉530519234
P粉530519234 2023-12-24 12:53:25
0
1
371

您好,我遇到一個問題,我的程式碼是:

if($user->plan->id == 1) {
    return view($this->activeTemplate . 'user.autopool', compact('pageTitle', 'commissions', 'deposit', 'transactions', 'commission', 'withdraw', 'transaction', 'username', 'balance', 'user', 'plans'));
} else {
    return view($this->activeTemplate . 'user.nopool', compact('pageTitle', 'user'));
}

我想從我的程式碼中消除這個錯誤。我被困在這裡了。

P粉530519234
P粉530519234

全部回覆(1)
P粉151466081

$user->plan 計算結果為 null。你不防備這一點。


  • 如果您使用的是 PHP8,則可以使用 nullsafe 運算子。
雷雷
  • 如果你使用的是 PHP7,你可以使用 laravel 的 optional() 函數。
雷雷
  • 如果 UserPlan 之間的關係是屬於關聯 (User ownsTo Plan),則最好在使用者模型中使用外鍵。
雷雷
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!