You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel访问hasOne关联属性时报Trying to get property of non-object错误

Fixing "Trying to get property of non-object" with Laravel HasOne Relationships

Hey there, let's break down why you're hitting this error and get it sorted out quickly!

The Root Cause

Your hasOne relationship setup is correct, but here's the catch: some of your Contact records don't have a corresponding PhoneNumber entry in the database. When that happens, $contact->phoneNumber returns null (not a PhoneNumber object), so trying to access ->number on a null value throws the "Trying to get property of non-object" error.

Quick Fixes

Here are a few straightforward ways to handle this:

  1. Optional Chaining (PHP 7.4+ / Laravel 8+)
    Use the null-safe operator ?-> to safely access the property only if the relationship exists:

    <li> 
        {{$contact->name}} 
        <small>by {{$contact->phoneNumber?->number}}</small>
    </li>
    

    If phoneNumber is null, this will output nothing (or null) instead of crashing.

  2. Laravel's optional() Helper
    If you need compatibility with older PHP versions, use the optional() helper function:

    <li> 
        {{$contact->name}} 
        <small>by {{optional($contact->phoneNumber)->number}}</small>
    </li>
    

    This does the same thing as optional chaining—it safely returns the property if the object exists, otherwise returns null.

  3. Existence Check in the View
    Explicitly check if the relationship exists before rendering the phone number:

    @foreach($contacts as $contact)
        <li> 
            {{$contact->name}} 
            @if($contact->phoneNumber)
                <small>by {{$contact->phoneNumber->number}}</small>
            @endif
        </li>
    @endforeach
    

    This way, the phone number line only shows up when there's a valid associated phone number.

Bonus: Optimize Performance & Avoid N+1 Queries

While you're at it, fix a common performance issue! Right now, your code runs a separate database query for each contact's phone number (that's the N+1 problem). Update your route to eager load the relationship:

Route::get('/', function (){ 
    $contacts = Contact::with('phoneNumber')->get(); 
    return view('welcome')->with('contacts',$contacts); 
});

This pulls all contacts and their associated phone numbers in just two queries, making your page load faster.

Double-Check Your Data

Just to be thorough, verify that your phone_numbers table has a contact_id foreign key linking to the contacts table, and that some contacts actually have matching entries there. It's totally normal for some contacts to lack phone numbers—our fixes above are designed to handle exactly that case!

内容的提问来源于stack exchange,提问作者sava milin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:32:37