phplaravel-5dynamic-properties

Laravel Checking if a Dynamic property is set


I have a class foo that belongs to bar.

within foo I have:

public function bar(){
    return $this->belongsTo('App\Models\Bar');
}

I have an object $foo who's bar_id is null.

Within Foo, I have an if statment:

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

Not surprisingly I was getting a Trying to get property of non-object error. So I added a call to isset. But now the code inside the if is never being evaluated because the if is always false. My new if looks like:

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

After setting the bar_id I am still not going into the if. When I try to print bar_id I see the value is not null. Why am I not going into this if?


Solution

  • I finally figured it out. Apparently isset doesn't call the dynamic function, which means that the value doesn't get loaded which means it is still null. To get around it I did the following:

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

    Since I am calling $this->bar() before it gets to the isset function, when isset checks the property, it returns True.