【问题标题】:Trying to get property of non-object, can't access to phoneNumber properties试图获取非对象的属性,无法访问 phoneNumber 属性
【发布时间】:2018-04-02 10:45:52
【问题描述】:
Route::get('/', function (){

$contacts = Contact::all();
//dd($contacts);

return view('welcome')->with('contacts',$contacts);

});

从我通过 $cotacts 到视图的路线

@foreach($contacts as  $contact)

    <li> {{$contact->name}}

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

    </li>

@endforeach

但是当我要访问phoneNumber的号码时,这是我的课:

public function phoneNumber()
    {
         return $this->hasOne(PhoneNumber::class);
    }

我收到错误试图获取非对象的属性 ???

当我这样说的时候:

<li> {{$contact->name}}

            <small>by {{$contact->phoneNumber}}</small>

        </li>

我得到: 科尔顿·基尔贝克四世{"id":20,"contact_id":1,"number":"+1-936-288-3493","created_at":"2018-04-01 20:14:16","updated_at":"2018-04-01 20:14:16"}

Shaun Streich DVM by

博士。 Ruthe Thiel III 作者

Laverne Mertz {"id":11,"contact_id":4,"number":"(769) 844-4643 x59321","created_at":"2018-04-01 20:14:16","updated_at":"2018-04-01 20:14:16"}

等等一些名字没有数字。

【问题讨论】:

    标签: php laravel-5 table-relationships


    【解决方案1】:

    问题是您的Contacts 没有关联的PhoneNumber,名称为Dr. Ruthe Thiel IIIShaun Streich DVM

    您可以在刀片模板中使用它:

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

    如果没有可用的电话号码,它将简单地省略电话号码。


    编辑:如果你想让输出更好一点,你也可以使用这样的东西:

    <li> {{$contact->name}}
        @if(count($contact->phoneNumber))
            <small>by {{$contact->phoneNumber->number}}</small>
        @else
            <small>has no known phone number</small>
        @endif
    </li>
    

    【讨论】:

    • 当我尝试第二次时,我得到同样的错误尝试获取非对象的属性,第一个解决方案 phpstorm 正在给我打电话?? Coalece 运算符仅在 PHP7 中可用,并且特征只能在 PHP 5.4 中使用,但是当我检查版本时,我有 PHP 7.1.9
    • 不确定您的 PHP 版本的错误,但我更新了 sn-p。我认为通过急切的加载,isset() 不起作用 - 但 count() 应该始终有效。
    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2014-12-09
    相关资源
    最近更新 更多