Can I in eloquent request to use diferent methods on condition?

  Kiến thức lập trình

In laravel 10 app when I need to read notifications of a user I do:

    if ($onlyUnread) {
        return auth()->user()->unreadNotifications()->latest()->paginate($backendPerPage);
    } else {
        return auth()->user()->notifications()->latest()->paginate($backendPerPage);
    }

I wonder if there is a way to write it in 1 line, like :

return auth()->user()->( $onlyUnread ? unreadNotifications() : notifications() )->latest()->paginate($backendPerPage);

?

LEAVE A COMMENT