So I loop through user notifications like so, in my Livewire Volt component:
#[Computed]
public function notifications()
{
return auth()->user()->fresh()->unreadNotifications;
}
Then in blade:
@forelse($this->notifications as $notification)
//Display notifications
@empty
No notifications
@endforelse
I have a little x
icon to mark a notification as read:
markAsRead('{{ $notification->id }}')
public function markAsRead(string $notificationId): void
{
auth()->user()->unreadNotifications()
->where('id', $notificationId)
->update(['read_at' => now()]);
}
Everything works. However, after the last notification has been marked as read, the text “No notifications” does not display. I first need a refresh. I’m trying to understand why I cannot get this to work.
Things I’ve tried:
public function markAsRead(string $notificationId): void
{
auth()->user()->unreadNotifications()
->where('id', $notificationId)
->update(['read_at' => now()]);
$this->dispatch('notificationsUpdated'); (or $this->dispatch('$refresh');)
}
And in the volt component:
protected $listeners = ['notificationsUpdated' => '$refresh'];
Also tried this instead:
public array $notifications = [];
public function mount()
{
$this->loadNotifications();
}
public function loadNotifications()
{
$this->notifications = auth()->user()->unreadNotifications;
}
public function markAsRead(string $notificationId): void
{
auth()->user()->unreadNotifications()
->where('id', $notificationId)
->update(['read_at' => now()]);
$this->loadNotifications();
}
Lastly I’ve tried:
public function loadNotifications()
{
$this->notifications = auth()->user()->fresh()->unreadNotifications;
}
Thinking this would reload a fresh user instance or something.
But the same “issue” keeps happening. I don’t want to show the user an empty block once the last notification has been marked as read, but I want it to show directly “No notifications” as stated in the @empty of the @forelse.
First and foremost I want to understand why this does not work. Any solution is of course a bonus.