Heim  >  Fragen und Antworten  >  Hauptteil

Ich versuche, die Null-Eigenschaft „id“ in Laravel 9 zu lesen

Hallo, ich bin auf ein Problem gestoßen, mein Code lautet:

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'));
}

Ich möchte diesen Fehler aus meinem Code beseitigen. Ich stecke hier fest.

P粉530519234P粉530519234274 Tage vor375

Antworte allen(1)Ich werde antworten

  • P粉151466081

    P粉1514660812023-12-25 00:10:31

    $user->plan evaluates to null. You don't guard against this.


    • 如果您使用的是 PHP8,则可以使用 nullsafe 运算符。
    if ($user->plan?->id)
    
    • If you're using PHP7, you can use laravel's optional() function.
    if (optional($user->plan)->id)
    
    • If the relationship between User and Plan is a belongsTo relationship (User belongsTo Plan), you might be better off just using the foreign key in the user model.
    if ($user->plan_id)
    

    Antwort
    0
  • StornierenAntwort