Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you an example of “How to Use isset in Relation data variable in blade file in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.
First, what we’re doing here, This is the example :
Let’s assume we have two tables one is for users and the second for user loan details, Whenever users register in the application user data will be stored in the user’s table, and then users apply for a loan, and we store both information in users and loan details table.
Sometimes users only register and not applied for a loan, then we only store the user information in the user’s table for a new Lead.
We created a relationship for the user’s table primary key as a foreign key in the loan table as user_id.
In the admin dashboard, we listed all the users with complete loan details, so there is a chance to some relations will return null values, because the user wants to only register, and loan entries are blank in the loan table, so the relationship will throw an error
“Trying to access array offset on the value of type null on view”, we can prevent this using multiple ways like empty, not empty and PHP ternary operators.
So we will use isset function in the Blade file to prevent this error.
Solution:-
Controller
$verifiedLoans = User::with('UserLoan')->where('is_verify','1')->get();
return view('loan.list',compact('verifiedLoans'));
Blade File
@if(isset($verifiedLoans))
@foreach ($verifiedLoans as $key => $user)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->mobile_no }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user['UserLoan']['loan_amount'] ?? '-' }}</td>
<td>
@if(isset($user['UserLoan']['loan_type']))
<span>{{ $user['UserLoan']['loan_type'] }}</span>
@endif
<td>{{ $user['UserLoan']['city'] ?? '-' }}</td>
<td>
@if(isset($user['UserLoan']['status']))
@if($user['UserLoan']['status'] == '1') Fresh @endif
@if($user['UserLoan']['status'] == '2') In-Process @endif
@endif
</td>
</tr>
@endforeach
@endif
Related article: – How to Check Collection is Empty or Not in Laravel 8.
In this article, we learned “Use isset in Relation data variable in Laravel blade file”, I hope this article will help you with your Laravel application Project.
Read also:- How to pass data to all views in Laravel 8.