Carol.Kar
Carol.Kar

Reputation: 5345

Eloquent - Trying to get property of non-object

I am using Laravel 5.5 and I am having the following query:

                $instru = Instruments::where('name', '=', $coinArr[$key])->first(); 
                $i = Revision::where('id', '=', $instru->revisions_id)->first();
                if ($i ===  NULL) { ...

In the setup case $instru = NULL hence the query on the Revision model does not work.

My problem is that I if I var_dump($i) I get the following error and do not run into the if-clause.

[2017-12-26 21:38:10] local.ERROR: Trying to get property of non-object  

Any suggestions how to deal with this case?

Upvotes: 0

Views: 62

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You should change:

$i = Revision::where('id', '=', $instru->revisions_id)->first();

into:

$i = $instru ? Revision::where('id', '=', $instru->revisions_id)->first() : null;

This is because in some cases $instru is null and you cannot run $instru->revisions_id when $instru is null

Upvotes: 3

Related Questions