php - Laravel Checking if a Dynamic property is set -


i have class foo belongs bar.

within foo have:

public function bar(){     return $this->belongsto('app\models\bar'); } 

i have object $foo who's bar_id null.

within foo, have if statment:

if ($this->bar->id == 1){ echo "in if"; } 

not surprisingly getting trying property of non-object error. added call isset. code inside if never being evaluated because if false. new if looks like:

if(isset($this->bar) && $this->bar->id == 1){ echo "in if"; } 

after setting bar_id still not going if. when try print bar_id see value not null. why not going if?

you can make safer check:

if($this->bar instanceof \app\models\bar) {     echo 'in if'; } 

this check if bar property set , according relation instantiated.


Comments