编程

Laravel optional 函数是如何工作的?

810 2023-04-04 18:55:00

这个方法允许你来获取对象的属性或者调用方法。如果该对象为 null,那么属性或者方法也会返回 null 而不是抛出错误

// User 1 exists, with account
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// User 2 exists, without account
$user2 = User::find(2);
$accountId = $user2->account->id; // PHP Error: Trying to get property of non-object
// Fix without optional()
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// Fix with optional()
$accountId = optional($user2->account)->id; // null

Tips: 该函数功能类似于 PHP 8.0 引入的新语法 - null 安全操作符。$country = $session?->user?->getAddress()?->country;