I'm working with Laravel 9 to develop a forum project, and I have used database
notifications for showing users new notifications such as best answer or etc.
The notifications list works correctly but shows the number of new notifications after the page refreshes. But I need to apply the ajax live update to get real-time applications user experience. So here is the notification-header
part, which shows the number of new notifications:
<div class="header__notification-btn" data-dropdown-btn="notification">
<i class="icon-Notification"></i>
@if(count(auth()->user()->unreadNotifications) != 0)
<span id="unreads">{{ digits_persian(count(auth()->user()->unreadNotifications)) }}</span>
@endif
<span style="display:none" id="elan"></span>
</div>
Then I tried applying the Ajax part like this:
notifcount = 0;
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: 'new-notifications-exists',
method: 'GET',
dataType: 'json',
success: function(response) {
if(notifcount == 0){
notifcount = response.notifcount;
}
if(response.notifcount > notifcount){
notifcount = response.notifcount;
new_notifications_found();
}
}
});
}, 2000);
});
function new_notifications_found(){
$("#unreads").hide();
$("#elan").show();
$("#elan").html("+.");
}
And this is the new-notifications-exists
URI handler:
Route::get('/new-notifications-exists', 'ToolsController@count_notifz');
Controller Method:
public function count_notifz()
{
if(Auth::check()){
$notiflist = DB::table('notifications')->where('notifiable_id',auth()->user()->id)->whereNull('read_at')->get();
$notifcount = $notiflist->count();
$response = array('notifcount' => $notifcount);
echo json_encode($response);
}
}
So: When I get a new notification, the <span style="display:none" id="elan"></span>
must be appeared because of the js function new_question_found()
which eventually hide #unreads
and show #elan
div instead.
But this thing does not work, and I get this error at the Console:
"No query results for model [App\Models\Question] new-notifications-exists"**
I don't know really what's going wrong here.
So if you have any idea about this or know how to apply ajax properly for these notifications, please let me know...
I would appreciate that.