阅读(4384)
赞(2)
Laravel 8 optional() {#collection-method}
2021-07-05 10:24:20 更新
optional 函数接受任何参数,并允许你访问该对象上的属性或调用其方法。如果给定对象为 null ,属性或方法将返回 null 而不是引发错误:
return optional($user->address)->street;
{!! old('name', optional($user)->name) !!} optional 函数也接受闭包作为其第二个参数。如果第一个参数提供的值不是 null,闭包将被调用:
return optional(User::find($id), function ($user) {
return new $user->name;
}); 
