D
D
Dmitry2018-03-19 15:44:37
Laravel
Dmitry, 2018-03-19 15:44:37

What causes the "Trying to get property of non-object" error?

Laravel.

$test = Tests::first();
return $test->name;

In this case, the code works without errors, but if I enter the condition:
$test = Tests::where('category_id','=',$category_id)->first();
return $test->name;

Here the error takes off:
Trying to get property of non-object and points to $test->name;
5b9d5e17b0fe2782516784.gif
What is this error from? Why does adding a condition ruin everything?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
imhuman, 2018-03-19
@imhuman

Apparently, there is no such category, respectively, there is no object and its properties, which is what the error text says

O
Oleg As, 2018-03-19
@eXcNightRider

If the query result is empty, first() will return NULL, it's worth checking $test for NULL before returning it
PS - if in where the first and third arguments should be equal, the second ('=') can be omitted and written
where('category_id',$category_id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question