Reputation: 2661
I have a controller for my website's inbox page, and in this controller there is a function that counts the number of unread messages the user has.
public function updateUnreadCount() {
if (Auth::check()) {
$value = 0;
$messages = Message::where(function($query) {
return $query->where('recipient_id', Auth::user()->id)->where('reci_read', 0)
->orWhere('user_id', Auth::user()->id)->where('sender_read', 0);
});
foreach ($messages as &$value) {
++$value;
};
Auth::user()->update([
'unread_msg' => $value,
]);
};
}
What I'd like to know is, how could I make this function trigger globally for all authenticated users, so that I could display the number of unread message on every page?
Upvotes: 2
Views: 68
Reputation: 74
refer http://culttt.com/2014/02/10/using-view-composers-laravel-4/
A View Composer is essentially just a piece of code that is executed and bound to a View whenever that View is requested.
For multiple pages You can also make this data available on multiple pages by adding a comma separated listed of Views.
View::composer(array('profile','dashboard'), function($view)
{
$view->with('count', Unread::updateUnreadCount());
});
Upvotes: 1
Reputation: 14027
Use View Composer
View composers are callbacks or class methods that are called when a view is rendered.
Say your unread inbox is located in navbar.blade.php
.
// From the documentation, using Closure based composers...
View::composer('navbar', function ($view) {
if(Auth::user()) {
//logic here
}
});
Upvotes: 1