Answer the question
In order to leave comments, you need to log in
Why does it throw an error in the view during foreach?
Hello, there are three tables which are connected by the relations.
In the controller, we pass data to the template:
$calculators = $request->user()->calculators()->get();
return view('test-view', [ 'temp' => $calculators ]);
echo $temp[0]->category->name;
echo $temp[0]->category->name;
// или
foreach ($temp as $calculator) {
echo '<pre>'; var_dump($calculator->category->name); echo '</pre>';
}
Trying to get property of non-object
Answer the question
In order to leave comments, you need to log in
When in the template I
echo $temp[0]->category->name;
then displays the name of the category, and if you run it through foreach:
Everything is very simple, one of the $calculator does not have a category, specifically the first one obviously does.
Check like this:
foreach ($temp as $key=>$calculator) {
echo (isset($calculator->category))?$calculator->category->name:'не задано для '.$key;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question