Reputation: 331
I have two table, one is User
that stores login credentials and other is Userinfo
that deals with storing personal information about the users. When a user sign up, they do not require filling up all the inputs for UserInfo
table (i.e. they might only fill up the Gender
and Religion
fields out of a few other). So, the end result is that the UserInfo
ends up being filled with only a couple of values or none at all.
The issue I am facing right now is when I pass through the data from both tables to view, and display them in typical laravel way, it throws an error Trying to get property of non-object
. This is expected since not all the users have complete data from UserInfo
table. I tried many methods both in controller and view to deal with the error message but failed to find a solution.
Is there a way to check the columns for empty or half complete value and deal with them properly in controller before passing onto the view? I think these checks should be performed in the controller or anywhere other than in the view. If there are none, how do I deal with them in the view? Maybe inside the loop? Solution and suggestions are greatly appreciated! Here's my code in the view:
@forelse($donors as $donor)
<div class="panel panel-default">
<div class="panel-heading"><i class="fa fa-list-alt"></i> {{$donor->name}}</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<div class="basic-info">
<h4>Basic Information</h4>
<p><strong>Blood Group: </strong>{{ $donor->user_info->blood }}</p>
<p><strong>Sex: </strong>{{ $donor->user_info->sex }}</p>
<p><strong>Religion: </strong>{{ $donor->user_info->religion }}</p>
<p><strong>Age: </strong>{{ \Carbon\Carbon::parse($donor->user_info->dob)->age }}</p>
</div>
</div>
</div>
</div>
</div>
@empty
<p>No records found!</p>
@endforelse
As you can see, because not all the user have complete data in the table, laravel throws the Trying to get property of non-object
error. My controller has standard laravel method of passing data to views:
public function index(User $user, Request $request)
{
$donors = $user->with('user_info')->latest()->paginate(5);
return view('donors.index', compact('donors'));
}
Upvotes: 1
Views: 764
Reputation: 7214
Since version 5.5, Laravel has an optional()
helper that I think it can help you.
Try something like this in your view:
optional($donor->user_info)->blood
Upvotes: 1