php - Laravel - 来自控制器全局的未读消息计数
问题描述
我有一个仪表板,您可以在其中查看有多少未读消息,但我希望在所有页面上使用此变量以在我的导航栏中创建一个徽章。如何将此变量返回给所有视图?
这是我的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'
));
}
}
解决方案
有三种不同的方法来解决您的挑战
* 中间件
* 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);
}
现在你可以在你的路由或路由组中附加这个中间件
基本控制器
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 调用。
如果想每隔几次更新一次通知,这很好。就像您可以每 5 秒进行一次 ajax 调用一样。
推荐阅读
- c++ - 打印出用户输入和条件之间可以被 2 和 3 整除的所有数字。while 循环要求另一个数字
- java - Java - 运行子进程在本地工作,但在 Heroku 上运行时因“管道损坏”而失败?
- pyspark - 从 pyspark 列中删除十进制值
- c++ - 将可执行文件加载到字符向量后的数据无效
- amazon-athena - Athena 分区投影和混合文件模式
- azure - App Insights 未从本地计算机发送
- python - 在python中不使用gcd查找整数列表的最小公倍数
- javascript - 在节点中返回承诺时出现 UnhandledPromiseRejectionWarning
- r - 在 R 中使用 pdf 函数模拟随机抽奖
- hive - 我认为我的 hql 是正确的,为什么我不能运行它?