尝试获取非对象的属性,无法访问电话号码属性


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

但是当我访问电话号码时,这是我的类:

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"}

肖恩·斯特赖希 DVM 由

鲁特·泰尔三世博士

拉文·默茨{"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"}

等等,有些名字没有数字。

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

可以改用在边栏选项卡模板中使用它:

<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>

最新更新