One to One
To check if there's a "one to one" relationship record, you can make use of the "isset" method when calling the relation.
if (isset($post->author)) { dd($post->author); }
One to Many
Since one to many is usually tied to "collection" you can make use of the "isEmpty" or "isNotEmpty" method.
if (isset($post->comments->isNotEmpty())) { dd($post->comments); } if (isset($post->comments->isEmpty())) { dd('There are no comments'); }
Optionally you can make use of the "optional" helper method to safely access any of the relationship properties. For the example below, if the "name" property exists and has value it will be returned, otherwise "null" value will be returned.
optinal($post->author)->name
Leave a reply