Search

Laravel Miscellaneous Helper Function: object_get

November 21, 2016 —John Koster

object_get($object, $key, $default = null)

The object_get allows developers to retrieve properties from a given $object using dot notation. This is useful in situations where it can not be guaranteed that a supplied object will have a given property, represented by the $key.

The following sample class structure will be used in the following examples:

1<?php
2 
3$sampleObject = new stdClass;
4$sampleObject->department = new stdClass;
5 
6$sampleObject->department->name = 'Marketing';

The department name can be retrieved like so:

1<?php
2 
3$departmentName = object_get($sampleObject, 'department.name');

The value of $departmentName would then be Marketing.

Attempting to retrieve the department's address would return NULL:

1<?php
2 
3// NULL
4$departmentAddress = object_get($sampleObject, 'department.address');

Or a different $default value can be supplied:

1<?php
2 
3// `No Address`
4$departmentAddress = object_get($sampleObject, 'department.address',
5 'No Address');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.