Reputation: 1643
Eager loading won't work work if the field has null
value. How do i escape the error
Trying to get property of non-object
and in model I set the relationship like this
public function bilstate()
{
return $this->hasOne('App\Attribute', 'at_id', 'cu_bilstateid');
}
can someone share the experience? Thanks
Upvotes: 2
Views: 1295
Reputation: 62368
For a hasOne
relationship, if the related record exists, the relationship attribute will be set to an instance of the related model; if the related record does not exist, the relationship attribute will be set to null.
The eager loading is working fine, you just need to check if the related model exists before trying to access anything on it.
if ($model->bilstate) {
echo 'bilstate exists: '.$model->bilstate->at_id;
} else {
echo 'bilstate does not exist. Don't access attributes or you'll get an exception.';
}
Note: you can use the is_null
method to check, if you'd like. However, using isset
or empty
is unreliable. If the relationship is not eager loaded, then the attribute will be lazy loaded using the __get()
magic method. is_null
will trigger this lazy load, whereas isset
and empty
will not.
Upvotes: 2