在 laravel 10 应用程序中,当我需要阅读用户的通知时,我会这样做:
if ($onlyUnread) {
return auth()->user()->unreadNotifications()->latest()->paginate($backendPerPage);
} else {
return auth()->user()->notifications()->latest()->paginate($backendPerPage);
}
我想知道是否有办法将其写成一行,例如:
return auth()->user()->( $onlyUnread ? unreadNotifications() : notifications() )->latest()->paginate($backendPerPage);
?
是的,您可以通过将三元运算符放在大括号内来在一行中完成此操作。
return auth()->user()->{ $onlyUnread ? 'unreadNotifications' : 'notifications' }()->latest()->paginate($backendPerPage);