【发布时间】:2020-07-09 07:23:27
【问题描述】:
在控制器中
public function index()
{
$profile = Profile::where('user_id', auth()->user()->id)->first();
return view('profile', compact('profile'));
}
在刀片视图中
<div class="card mb-5">
<img class="card-img-top" src="{{ asset('images/'.$profile->image ? $profile->image : "" ) }}"
alt="Profile User">
<div class="card-body">
<h5 class="card-title">{{Auth::user() ? Auth::user()->name :""}}</h5>
<p class="card-text">{{Auth::user() ?Auth::user()->email :""}}.</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">{{$profile ? $profile->gender :"Belum Di isi"}}</li>
<li class="list-group-item">{{$profile ? $profile->phone :"Belum Di isi"}}</li>
<li class="list-group-item">{{$profile ? $profile->address :"Belum Di isi"}}</li>
</ul>
</div>
但是上面的代码抛出一个错误 Trying to get property of non-object。 如何修复这些错误,使图像再次运行而不会出现错误
【问题讨论】:
-
显示 $profile 的 dd(),在你的控制器中添加 dd($profile) 。它会给出同样的错误吗?
-
当dd($profile)结果为null时
-
它显示该错误,因为您的 $profile 对象为空。在访问其属性之前,您应该先检查它。你应该试试这个
$profile ? $profile->image : "" -
我认为数据不存在,这就是您收到此错误的原因。如果是这样,则将
first()更改为firstOrFail如果不存在数据,它将引发 404 错误。$profile = Profile::where('user_id', auth()->user()-id)->firstOrFail(); -
我试过了还是报错