我可以雄辩地要求根据条件使用不同的方法吗?

问题描述 投票:0回答:1

在 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);

laravel
1个回答
0
投票

是的,您可以通过将三元运算符放在大括号内来在一行中完成此操作。

return auth()->user()->{ $onlyUnread ? 'unreadNotifications' : 'notifications' }()->latest()->paginate($backendPerPage);
© www.soinside.com 2019 - 2024. All rights reserved.