Hi Devs, In Laravel when accessing a relationship property we not sure whether the relationship data exists. if exists it's good to go. but what if not exists those times we get the following Warning;
Consider the Below code
$user = User::findOrFail(1);
$subscription = $user->subscription->created_at;
PHP Notice: Trying to get property 'created_at' of non-object in /Users/benittoraj/code/laravel/mas-laraveleval()'d code on line
To Avoid the above error we often use optional helper function.
$subscriptionCreatedAt= optional($user->subscription)->created_at;
Do You know there is another way of handling this using object_get helper function
$subscriptionCreatedAt = object_get($user, 'subscription.created_at);
The Nice thing about object_get helper function is we can access the relationship relation property using dot syntax. So our code looks clean. If some relation data does't exists it stops there and return null;
[object_get helper implementation](https://github.com/illuminate/support/blob/master/helpers.php#:~:text=*/-,function%20object_get(%24object%2C%20%24key%2C%20%24default,%7D,-%7D)
Keep Learning!!
Top comments (1)
Another cool way is to use the "Default Models" feature on a relation:
If it was implemented on your
subscription
relation you can always get$user->subscription->created_at
without errors, butcreated_at
would benull
.