N
N
Nikolay2017-05-26 11:53:46
Laravel
Nikolay, 2017-05-26 11:53:46

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 ]);

When I display in the template
echo $temp[0]->category->name;
, it displays the name of the category, and if so:
echo $temp[0]->category->name;
// или
foreach ($temp as $calculator) {
    echo '<pre>'; var_dump($calculator->category->name); echo '</pre>';
}

then it ends with an error.
Trying to get property of non-object

All entities have categories specified.
How can I get the category name?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
IceJOKER, 2017-05-26
@IceJOKER

When in the template I
echo $temp[0]->category->name;
then displays the name of the category, and if you run it through foreach:

Because in this way you display the name of the category of the first entity, and foreach passes through all, it means that some entity does not have a category

M
Maxim Timofeev, 2017-05-26
@webinar

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 question

Ask a Question

731 491 924 answers to any question