diff --git a/src/Illuminate/Support/Optional.php b/src/Illuminate/Support/Optional.php index 8f35221ad2c0..7f7faab1ce2d 100644 --- a/src/Illuminate/Support/Optional.php +++ b/src/Illuminate/Support/Optional.php @@ -37,7 +37,7 @@ public function __construct($value) public function __get($key) { if (is_object($this->value)) { - return $this->value->{$key}; + return $this->value->{$key} ?? null; } } diff --git a/tests/Support/SupportHelpersTest.php b/tests/Support/SupportHelpersTest.php index e173ae108785..1e612741b5ad 100755 --- a/tests/Support/SupportHelpersTest.php +++ b/tests/Support/SupportHelpersTest.php @@ -786,15 +786,16 @@ public function something() public function testOptionalWithArray() { - $this->assertNull(optional(null)['missing']); - $this->assertEquals('here', optional(['present' => 'here'])['present']); + $this->assertNull(optional(null)['missing']); + $this->assertNull(optional(['present' => 'here'])->missing); } public function testOptionalReturnsObjectPropertyOrNull() { $this->assertSame('bar', optional((object) ['foo' => 'bar'])->foo); $this->assertNull(optional(['foo' => 'bar'])->foo); + $this->assertNull(optional((object) ['foo' => 'bar'])->bar); } public function testOptionalDeterminesWhetherKeyIsSet()