正确检查状态通知Laravel

时间:2018-01-21 19:18:28

标签: php laravel

我有代码:

static public function alerts() {
    $user = Auth::user();
    $alerts = [];
    foreach ($user->unreadNotifications as $notification) {
        switch($notification->type) {
            case 'App\Notifications\OrderTracker':
                $alerts['order'] = $notification->type;
            break;
            case 'App\Notifications\ReviewTracker':
                $alerts['review'] = $notification->type;
            break;
        }
            $alerts['all'] = $notification->type;
    }

    return ($user->unreadNotifications) ? $alerts : null;
}

在刀片中我想按类型通知计数通知:

Orders {{ count(Helper::alerts()['orders']) }}
Reviews {{ count(Helper::alerts()['reviews']) }}
All {{ count(Helper::alerts()['all']) }}
我认为,这个拐杖并没有正确。我如何轻松查看通知类型?

2 个答案:

答案 0 :(得分:0)

你可以这样做。此代码将只为DB创建一个查询。此外,如果您要添加更多通知类型,则此代码将更易于维护。

static public function alerts() {
    $types = [
        'order' => 'App\Notifications\OrderTracker',
        'review' => 'App\Notifications\ReviewTracker'
    ];
    foreach ($types as $key => $type) {
        $alerts[$key] = auth()->user()->unreadNotifications->where('type', $type)->count();
    }
    return $alerts['all'] = array_sum($alerts) ? $alerts : null;
}

答案 1 :(得分:0)

他想要一些简单的东西

static public function alerts() {
  $user = Auth::user();
  $alerts = [
    'orders'=>0,
    'review'=>0,
    'all'=>0
  ];

 foreach ($user->unreadNotifications as $notification) {
    switch($notification->type) {
        case 'App\Notifications\OrderTracker':
            $alerts['order'] +=1; 
        break;
        case 'App\Notifications\ReviewTracker':
            $alerts['review'] +=1;
        break;
    }
        $alerts['all']+=1;
 }

    return ($user->unreadNotifications) ? $alerts : null;
}