DEV Community


Posted on

Laravel: object _get Alternative for optional Helper Function

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Do You know there is another way of handling this using object_get helper function

$subscriptionCreatedAt = object_get($user, 'subscription.created_at);
Enter fullscreen mode Exit fullscreen mode

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](*/-,function%20object_get(%24object%2C%20%24key%2C%20%24default,%7D,-%7D)

Keep Learning!!

Top comments (1)

stayallive profile image
Alex Bouma

Another cool way is to use the "Default Models" feature on a relation:

The belongsTo, hasOne, hasOneThrough, and morphOne relationships allow you to define a default model that will be returned if the given relationship is null. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user relation will return an empty App\Models\User model if no user is attached to the Post model:

 * Get the author of the post.
public function user()
    return $this->belongsTo(User::class)->withDefault();


If it was implemented on your subscription relation you can always get $user->subscription->created_at without errors, but created_at would be null.