我有一个仪表板,您可以在其中查看收到的未读邮件数量,但是我希望在所有页面上使用此变量在导航栏中创建徽章。如何将此变量返回所有视图?
这是我的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'
));
}
}
答案 0 :(得分:1)
有三种解决挑战的方法
*中间件
* 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调用。
如果要每隔几次更新通知,这很好。就像您可以每5秒拨打一次ajax电话。