Yet another helper function in Laravel optional()
that allows you to access properties or methods of a given object. If the given object is null
, the property or method will return null
instead error
.
Take a look at the example below.
// app/Models/User.php
class User extends Model
{
//...
public function account()
{
//...
}
//...
}
// user1 存在,account 对象也存在
$user1 = User::find(1);
$accountId = $user1->account->id; // 123
// user2 存在,但是 account 对象不存在
$user2 = User::find(2);
$accountId = $user2->account->id; //这时会报: PHP Error: Trying to get property of non-object
// 如果不用 optional(), 你可能会这么判断
$accountId = $user2->account ? $user2->account->id : null; // null
$accountId = $user2->account->id ?? null; // null
// 用 optional(),简单搞定,是不看起来很优雅呢
$accountId = optional($user2->account)->id; // null
optional()
Helpers are ideal when working with unavailable objects or when calling nested data in unavailable Eloquent relationships .
You might as well try it ^_^
For more PHP knowledge, go to PHPCasts