У меня есть панель инструментов, на которой вы можете увидеть, сколько у вас непрочитанных сообщений, но я хочу, чтобы эта переменная использовалась на всех страницах для создания значка на моей панели навигации. Как я могу вернуть эту переменную во все представления?
Это мой 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'
));
}
}
Я думаю, что проще всего было бы Middleware или композитор представлений, как предложено выше.
Можно ли добавить к провайдеру классы приложений? используйте приложение \ билет; используйте App \ TicketMessage;






Есть три разных способа решить вашу задачу
* Промежуточное ПО
* 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
Создайте функцию / контроллер и верните количество уведомлений как return
class NotificationCounterController extends Controller
{
function getNotificatioCount()
{
$notificationCount = 1;
return ['count' => $notificationCount];
}
}
и не вы можете сделать вызов ajax в событии загрузки документа.
this is good if want to update notification in every few time. like you can make ajax call in every 5 second.
Вам нужно посмотреть на композиторов - laravel.com/docs/5.6/views#sharing-data-with-all-views.