Laravel - количество непрочитанных сообщений от контроллера global - PullRequest
0 голосов
/ 07 сентября 2018

У меня есть панель инструментов, где вы можете увидеть, сколько непрочитанных сообщений вы получили, но я хочу, чтобы эта переменная использовалась на всех страницах для создания значка на моей панели навигации. Как я могу вернуть эту переменную во все представления?

Это мой DashboardController:

class DashboardController extends Controller
{

public function index()
{
    $spentAmount = 0;
    $ordersPending = 0;
    $ordersCancelled = 0;
    $ordersCompleted = 0;
    $ordersPartial = 0;
    $ordersInProgress = 0;
    $orders = Auth::user()->orders;
    $ticketIds = Ticket::where(['user_id' => Auth::user()->id])->get()->pluck('id')->toArray();
    $unreadMessages = TicketMessage::where(['is_read' => 0])->whereIn('ticket_id', $ticketIds)->whereNotIn('user_id', [Auth::user()->id])->count();
    $supportTicketOpen = Ticket::where(['status' => 'OPEN', 'user_id' => Auth::user()->id])->count();

    foreach ($orders as $order) {
        if (strtolower($order->status) == 'pending') {
            $spentAmount += $order->price;
            $ordersPending++;
        } elseif (strtolower($order->status) == 'cancelled') {
            $ordersCancelled++;
        } elseif (strtolower($order->status) == 'completed') {
            $spentAmount += $order->price;
            $ordersCompleted++;
        } elseif (strtolower($order->status) == 'partial') {
            $spentAmount += $order->price;
            $ordersCompleted++;
        } elseif (strtolower($order->status) == 'inprogress') {
            $ordersInProgress++;
        }
    }
    return view('dashboard', compact(
        'spentAmount',
        'ordersPending',
        'ordersCancelled',
        'ordersCompleted',
        'unreadMessages',
        'ordersPartial',
        'supportTicketOpen',
        'ordersInProgress'
    ));


}

}

1 Ответ

0 голосов
/ 07 сентября 2018

Есть три разных способа решения вашей задачи

* Промежуточное программное обеспечение
* BaseClass
* JavaScript

промежуточное ПО и базовый контроллер аналогичны


Промежуточное программное обеспечение

public function handle($request, Closure $next)
{
    $notificationCount = 1;// query the database here and get notification for your

    // add $notificationCount to your request instance
    $request->request->add(['notificationCount' => $notificationCount]);

    // call the middleware next method and you are done.
    return $next($request);
}

и теперь вы можете прикрепить это промежуточное ПО к вашим маршрутам или группе маршрутов


BaseController

class MyController extends Controller
{
    function __construct()
    {
        $this->middleware(function ($request, $next) {

            $notificationCount = 1;// query the database here and get notification for your

            // add $notificationCount to your request instance
            $request->request->add(['notificationCount' => $notificationCount]);

            // call the middleware next method and you are done.
            return $next($request);
        });
    }
}

и теперь вы можете расширить свой контроллер с MyController вместо Controller, а затем вы можете использовать что-то подобное

{{ request('notificationCount') }}

Javascript

Создайте функцию / контроллер и верните количество уведомлений как возвращаемое

class NotificationCounterController extends Controller
{
    function getNotificatioCount()
    {
        $notificationCount = 1;
        return ['count' => $notificationCount];
    }
}

и нельзя делать вызов ajax при событии загрузки документа.

это хорошо, если вы хотите обновлять уведомления каждые несколько раз. как вы можете совершать ajax-вызовы каждые 5 секунд.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...