在导航栏上显示通知计数


Laravel - display notification count on navigation bar

目前我在我的旅游应用程序通知功能。通知不需要是实时的,用户只需刷新页面,然后系统将再次获得最新的通知计数,并显示在导航栏的顶部。我通过在基本控制器中实现get count函数实现了这一点所有其他控制器都将从它扩展。下面是我如何获得通知计数的示例。

我有两个表,ap_threadap_thread_comment。ap_thread有一个列last_visit_date, ap_thread_comment有一个列created_at。一个线程可以有很多评论,我只是查询像ap_thread_comment created_date> ap_thread last_visit_date,并获得总未读评论。当线程所有者访问他们的线程时,ap_thread last_visit_date将更新。

现在的问题是,当一些用户评论线程,让我们说2未读评论。但是当线程所有者再次访问他们的线程时,它将显示2个未读评论,这是因为基础控制器将首先触发,而不是只跟随控制器更新last_visit_date。如果我再次刷新页面,我可以得到正确的计数。我这样执行通知是错的吗?下面是我的代码

class BaseController extends Controller{
public function __construct() {
   $new_thread_comment_count = 50; // 50 unread comments for example.
   View::share('new_thread_comment_count', $new_thread_comment_count);
}
class ThreadController extends BaseController{
   // update last visit date function
}

我假设这是在设置线程注释计数时使用的。由于您是在方法的构造函数中调用它,因此您在过程中过早地获得了未读计数。

我建议你实际上使用视图编写器而不是使用View::share()。视图作曲家本质上是给你一个延迟计算,因为它们是在视图被渲染之前被调用的。

您可以在register方法中将视图编写器附加到应用程序服务提供者中的;

// '*' will attach this composer to all views, if you want only a single view
// specify it's name, or you can specify an array of views.
view()->composer('*', function (View $view) {
    $new_thread_comment_count = 50;
    $view->with('new_thread_comment_count', $new_thread_comment_count);
});

如作曲家文档中所述,如果你不喜欢闭包或在你的服务提供者中放入太多逻辑,那么你可以在那里放入一个命名类;

view()->composer('*', 'App'Http'ViewComposers'NewThreadCommentCounter');