Darren Lau
Darren Lau

Reputation: 2055

Laravel - display notification count on navigation bar

currently im working on a notification features in my laravel apps. The notification doesn't need to be real time, users just refresh the page then the system will get latest notification count again and display on top of the navigation bar. I've achieved this by implementing the get count function in my base controller all my other controller will extend from it. Below is the example of how i get the notification count.

I've two table, ap_thread and ap_thread_comment. ap_thread has a column last_visit_date and ap_thread_comment has a column created_at. One thread can have many comments, i simply query like when ap_thread_comment created_date is > than the ap_thread last_visit_date and getthe total unread comment. The ap_thread last_visit_date will update when the thread owner visit their thread.

Now the problem is when some user comment on the thread let's say 2 unread comments. But when the thread owner visit to their thread again, it will show 2 unread comments it's because the base controller will trigger first than only follow by the controller to update the last_visit_date. I can get the correct count if i refresh the page again. Am i doing wrong to implement the notification like this? Below is my code

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
}

Upvotes: 2

Views: 5445

Answers (1)

marcus.ramsden
marcus.ramsden

Reputation: 2633

I would assume that this is to do with when you are setting up your thread comment count. Since you are calling it in the constructor of your method you are getting the unread count too early in proceedings.

I would suggest instead of using View::share() that you actually use a view composer. View composers essentially give you a lazy evaluation as they are called just before the view is rendered.

You could attach the view composer in your application service provider in the register method with;

// '*' 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);
});

As noted in the documentation for composers if you aren't a fan of closures or putting too much logic into your service providers then you can put a named class in there;

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

Upvotes: 4

Related Questions