'Attempt to read property "degree" on null
i have created a profile where users can add their education fields.
when there is no value in the database it throws an error. how can i get rid of this ? Attempt to read property "degree" on null.
public function myEducations()
{
return $this->hasMany('App\Models\Education','user_id')->orderByDesc('endDate');
}
controller
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 }}
Solution 1:[1]
If the users of you application are filling in their education details later only. You should ideally catch this condition when rendering your view. For example you could try the following:
@if ($education)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
<p>Education details not available</p>
@endif
Solution 2:[2]
You have to inspect in an if statement $education->degree is not null. If not null, degree has value, this part will render. Else, it doesn't have value so else block appears in template.
@if(null !== $education->degree)
{{ $education->degree }} - {{ $education->fieldOfStudy }}
@else
// there is no degree
@endif
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jibin Bose |
Solution 2 |