尝试在 null 上读取 属性 "degree"
Attempt to read property "degree" on null
我已经创建了一个配置文件,用户可以在其中添加他们的教育领域。
当数据库中没有值时,它会抛出错误。我怎样才能摆脱这个?尝试在 null 上读取 属性“学位”。
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
控制器
public function myProfile(\App\Models\User $user)
{
$user = Auth::user();
$education = $user->myEducations->first();
return view('candidate.profile',compact('user','education'));
blade
{{ $education->degree }} - {{ $education->fieldOfStudy }}
您必须在 if 语句中检查 $education->degree 不为空。
如果不为空,度数有值,这部分会渲染。
否则,它没有价值,所以 else 块出现在模板中。
@if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
// there is no degree
@endif
如果您的应用程序的用户稍后才填写他们的教育详细信息。理想情况下,您应该在渲染视图时捕捉到这种情况。例如,您可以尝试以下操作:
@if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
<p>Education details not available</p>
@endif
我已经创建了一个配置文件,用户可以在其中添加他们的教育领域。
当数据库中没有值时,它会抛出错误。我怎样才能摆脱这个?尝试在 null 上读取 属性“学位”。
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
控制器
public function myProfile(\App\Models\User $user)
{
$user = Auth::user();
$education = $user->myEducations->first();
return view('candidate.profile',compact('user','education'));
blade
{{ $education->degree }} - {{ $education->fieldOfStudy }}
您必须在 if 语句中检查 $education->degree 不为空。 如果不为空,度数有值,这部分会渲染。 否则,它没有价值,所以 else 块出现在模板中。
@if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
// there is no degree
@endif
如果您的应用程序的用户稍后才填写他们的教育详细信息。理想情况下,您应该在渲染视图时捕捉到这种情况。例如,您可以尝试以下操作:
@if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
<p>Education details not available</p>
@endif