This code displays the respondent infected with the diseases and date ranges from the selected dropdowns, I want to display the household where that respondent belongs to and the purok which the household belongs to.
But when I tried to access the purok it says Attempt to read property "puroks" on null.
View
@foreach($infectedRespondents as $household)
<tr>
<td>{{ $household->id }}</td>
<td>{{ $household->household->puroks->purok_num }}</td>
<td>{{ $household->name }}</td>
</tr>
@endforeach
Controller
public function getInfected(Request $request)
{
$SDOHs = SDOH::all();
$categories = SDOHCategory::all();
$HDs = HD::all();
$diseases = Disease::all();
$vaccines = Vaccine::all();
$envHazards = EnvHazard::all();
$puroks = Purok::all();
$households = HouseholdHead::with('categoryHouseholds.sdoh_category')->get();
$respondents = Respondent::with('household_heads')->get();
$selectedDiseaseId = $request->input('disease');
$startDate = $request->input('start');
$endDate = $request->input('end');
$infectedRespondents = Respondent::whereHas('diseases',
function ($query) use ($selectedDiseaseId, $startDate, $endDate) {
$query->where('disease_id', $selectedDiseaseId)
->whereBetween('date', [$startDate, $endDate]);
})
->with(['household_heads.puroks'])
->get();
return view('filtered_map',
compact('households', 'SDOHs', 'categories', 'diseases', 'vaccines', 'envHazards', 'respondents', 'puroks',
'HDs', 'infectedRespondents'));
}
household_heads table has purok_id column reference to puroks table. respondents table and household_heads table have pivot table such as respondent_households table with respondent_id and household_head_id foreign keys.
I am new to Laravel which is why eloquent and pivot tables are still confusing for me.
2
Answers
You should check if the household relationship exists before accessing the puroks relationship. You can use the
optional()
helper function.When using PHP 8.0 or later versions, the nullsafe operator (?->) helps prevent ‘trying to get property of non-object’ errors when accessing properties or methods on potentially null objects.
In your Blade template, you can use the nullsafe operator as follows:
This usage allows for safe navigation through potentially null relationships. If any part of the chain (household_heads or puroks) is null, it gracefully returns null instead of throwing an error.
You can use optional() in Laravel with PHP versions 7.3 and newer.
First
optional()
or?->
: Checks if $respondent->household_heads is null.If not null, it accesses ->puroks; if null, it returns null.
Second
optional()
or?->
: Checks if the result of the firstoptional() or ?->
is null.If not null, it accesses ->purok_name; if null, it returns null.