Notification center

The bell in the shell's top row, with the unread count on it, and what it opens: the latest notifications, new ones first, each marked read on its own or all at once, with an invitation accepted or declined where it stands. On a desktop they hang from the bell in a popover; on a phone they come in a drawer. Every notification is on a page of its own as well, with All and Unread.

The notifications open from the bell, light and dark

The notifications on a phone, light and dark

A block, not a component: copy the views below into your app. The bell is drawn by both app shells, which assume the base layout. The rows are Laravel's database notifications; the views read them as arrays, so a DatabaseNotification (which reads the same way) drops straight in.

What it shows

  • The bell: a button with the unread count as its badge, and the count in its name too ("Notifications, 3 unread"), since the badge is drawn only.

  • The list, a notification list: the count beside the heading, Mark all as read, the unread under "New" and the rest under "Earlier". An unread row has a tint, a dot, "Unread:" before its title for a screen reader, and a Mark as read button (the tick), which dispatches read with the row's id. Each row is a link, through a route that marks it read on the way to the thing it is about.

  • Inline actions: an invitation carries Accept and Decline, each a form that posts, in the row.

  • A popover on a desktop, a drawer on a phone, with the same list in each. The bell is two buttons, one shown at each width, since the popover has no smaller form of its own; the phone's drawer holds focus and gives the list the whole height.

  • Nothing new: no badge on the bell, and a list that says so:

    No notifications, light and dark

  • All notifications, a page of its own, linked from the foot of the list: Mark all as read and Settings in the page header, All and Unread as navigation tabs (links, so the filter is in the URL and the Back button), twenty to a page with Laravel's paginator drawn by the package's ds::pagination view:

    The notifications page, light and dark

    The notifications page on a phone, light and dark

    The Unread tab with nothing unread says "Nothing unread" rather than the empty state of a new account.

Built from

  • Button: the bell, with its badge; Mark all as read, Accept, Decline, Settings
  • Popover: the list under the bell on a desktop
  • Drawer: the list on a phone
  • Notification list: the list, its groups and rows
  • Page header and Tabs: the notifications page
  • Panel: the card the page's list sits in

The markup

resources/views/components/notification-bell.blade.php

{{--
    The bell in the shell's top row: a popover under it on a desktop, a
    drawer on a phone, both holding the same panel, and a link to the
    notifications page with no script. $notifications are the
    latest few and $unread the count, from the layout's view composer; the
    Livewire version on the docs page keeps them fresh.
--}}
@props(['notifications' => [], 'unread' => 0])

@php
    // The badge is drawn only, so the count is in the name too.
    $name = $unread ? "Notifications, {$unread} unread" : 'Notifications';
@endphp

<div x-data="{ notificationsOpen: false }" class="flex">
    {{-- With no script to open either, the bell is a link to the page of them all. --}}
    <x-ds::button
        variant="ghost"
        icon="bell"
        :iconOnly="true"
        :badge="$unread ?: null"
        :href="route('notifications.index')"
        :aria-label="$name"
        class="[@media(scripting:enabled)]:hidden"
    />

    <x-ds::popover labelledby="notifications-popover-title" width="lg" placement="bottom-end" class="max-lg:hidden [@media(scripting:none)]:hidden">
        <x-slot:trigger>
            <x-ds::button variant="ghost" icon="bell" :iconOnly="true" :badge="$unread ?: null" :aria-label="$name" />
        </x-slot:trigger>

        <x-notification-panel id="notifications-popover" :notifications="$notifications" :unread="$unread" class="-m-4" />
    </x-ds::popover>

    {{-- A phone has no room for a popover: the bell opens a drawer, drawn only while open. --}}
    <x-ds::button
        variant="ghost"
        icon="bell"
        :iconOnly="true"
        :badge="$unread ?: null"
        :aria-label="$name"
        aria-haspopup="dialog"
        x-on:click="notificationsOpen = true"
        class="lg:hidden [@media(scripting:none)]:hidden"
    />
    <x-ds::drawer open="notificationsOpen" side="right" size="sm" label="Notifications">
        <template x-if="notificationsOpen">
            {{-- The drawer has no title bar, the list has its own heading: its head row leaves room for the drawer's Close in the corner. --}}
            <x-notification-panel id="notifications-drawer" :notifications="$notifications" :unread="$unread" class="-mx-5 -my-4 [&>div:first-child]:pe-14" />
        </template>
    </x-ds::drawer>
</div>

resources/views/components/notification-panel.blade.php

{{--
    The list the bell opens: the latest notifications, Mark all as read,
    and the way to the full page. Drawn in the popover and in the phone's
    drawer, so it takes an id for each.
--}}
@props(['id', 'notifications' => [], 'unread' => 0])

<x-ds::notification-list
    :id="$id"
    :unread="$unread"
    emptyDescription="Mentions, reviews and invitations will show up here."
    :footerHref="route('notifications.index')"
    {{ $attributes }}
>
    @if ($unread)
        <x-slot:actions>
            <form method="POST" action="{{ route('notifications.read-all') }}">
                @csrf
                <x-ds::button type="submit" variant="ghost" size="sm">Mark all as read</x-ds::button>
            </form>
        </x-slot:actions>
    @endif

    <x-notification-rows :notifications="$notifications" />
</x-ds::notification-list>

resources/views/components/notification-rows.blade.php

{{--
    The rows, unread first under "New", the rest under "Earlier": shared by
    the bell's panel and the notifications page. Each is a Laravel database
    notification (or an array of the same shape) whose data holds title,
    body, icon, tone and, for an invitation, its id. A row links through
    notifications.show, which marks it read and goes on to the thing.
--}}
@props(['notifications' => []])

@php
    [$new, $earlier] = collect($notifications)->partition(fn ($n) => $n['read_at'] === null);
@endphp

@foreach (['New' => $new, 'Earlier' => $earlier] as $label => $rows)
    @continue($rows->isEmpty())
    <x-ds::notification-group :label="$label">
        @foreach ($rows as $notification)
            @php $data = $notification['data']; @endphp
            <x-ds::notification-item
                :id="$notification['id']"
                :title="$data['title']"
                :href="route('notifications.show', $notification['id'])"
                :time="$notification['created_at']"
                :unread="$notification['read_at'] === null"
                :icon="$data['icon'] ?? 'bell'"
                :tone="$data['tone'] ?? 'neutral'"
                wire:key="notification-{{ $notification['id'] }}"
            >
                {{ $data['body'] ?? '' }}

                @isset($data['invitation'])
                    <x-slot:actions>
                        <form method="POST" action="{{ route('invitations.accept', $data['invitation']) }}">
                            @csrf
                            <x-ds::button type="submit" size="sm">Accept</x-ds::button>
                        </form>
                        <form method="POST" action="{{ route('invitations.decline', $data['invitation']) }}">
                            @csrf
                            <x-ds::button type="submit" size="sm" variant="secondary">Decline</x-ds::button>
                        </form>
                    </x-slot:actions>
                @endisset
            </x-ds::notification-item>
        @endforeach
    </x-ds::notification-group>
@endforeach

resources/views/notifications/index.blade.php

{{--
    Every notification, twenty to a page, with All and Unread as links so
    the filter is in the URL. The controller passes $notifications (a
    paginator), $filter (all or unread) and $unread (the count).
--}}
<x-layouts.app title="Notifications">
    <div class="flex flex-col gap-6">
        <x-ds::page-header title="Notifications" description="Mentions, reviews and invitations from Tidewater Ferries.">
            <x-slot:actions>
                @if ($unread)
                    <form method="POST" action="{{ route('notifications.read-all') }}">
                        @csrf
                        <x-ds::button type="submit" variant="secondary" icon="check">Mark all as read</x-ds::button>
                    </form>
                @endif
                <x-ds::button variant="secondary" icon="cog-6-tooth" :href="route('settings.notifications')">Settings</x-ds::button>
            </x-slot:actions>

            <x-slot:tabs>
                <x-ds::tabs label="Which notifications" :navigation="true">
                    <x-ds::tab :href="route('notifications.index')" :active="$filter === 'all'">All</x-ds::tab>
                    <x-ds::tab :href="route('notifications.index', ['filter' => 'unread'])" :active="$filter === 'unread'" :count="$unread">Unread</x-ds::tab>
                </x-ds::tabs>
            </x-slot:tabs>
        </x-ds::page-header>

        <x-ds::panel>
            <x-ds::notification-list
                id="notifications-page"
                :title="$filter === 'unread' ? 'Unread' : 'All notifications'"
                :emptyTitle="$filter === 'unread' ? 'Nothing unread' : 'No notifications yet'"
                :emptyDescription="$filter === 'unread' ? 'You have read everything. New mentions and reviews will show up here.' : 'Mentions, reviews and invitations will show up here.'"
            >
                <x-notification-rows :notifications="$notifications->items()" />
            </x-ds::notification-list>
        </x-ds::panel>

        {{ $notifications->withQueryString()->links('ds::pagination') }}
    </div>
</x-layouts.app>

Wire it up

The data

The layout's view composer (see the sidebar shell) hands the bell unreadCount and latestNotifications:

'unreadCount' => $user->unreadNotifications()->count(),
'latestNotifications' => $user->notifications()->latest()->limit(8)->get(),

These are Laravel's database notifications. The rows read title, body, icon (a Heroicons name), tone and, for an invitation, invitation (its id) from each one's data, and the route a row links through reads url, where it leads; so a notification's toArray() returns those:

public function toArray(object $notifiable): array
{
    return [
        'title' => "{$this->author->name} mentioned you on {$this->issue->key}",
        'body' => '“'.Str::limit($this->comment->body, 120).'”',
        'icon' => 'chat-bubble-left-ellipsis',
        'tone' => 'accent',
        'url' => route('issues.show', $this->issue->key).'#comment-'.$this->comment->id,
    ];
}

The routes

Route::get('notifications', [NotificationController::class, 'index'])->name('notifications.index');
Route::get('notifications/{notification}', [NotificationController::class, 'show'])->name('notifications.show');
Route::post('notifications/read-all', [NotificationController::class, 'readAll'])->name('notifications.read-all');
Route::post('invitations/{invitation}/accept', [InvitationController::class, 'accept'])->name('invitations.accept');
Route::post('invitations/{invitation}/decline', [InvitationController::class, 'decline'])->name('invitations.decline');
class NotificationController
{
    public function index(Request $request)
    {
        $filter = $request->query('filter') === 'unread' ? 'unread' : 'all';
        $user = $request->user();

        return view('notifications.index', [
            'notifications' => ($filter === 'unread' ? $user->unreadNotifications() : $user->notifications())
                ->latest()
                ->paginate(20),
            'filter' => $filter,
            'unread' => $user->unreadNotifications()->count(),
        ]);
    }

    // A row is a link through here: it is read once it is followed.
    public function show(Request $request, string $notification)
    {
        $notification = $request->user()->notifications()->findOrFail($notification);
        $notification->markAsRead();

        return redirect($notification->data['url'] ?? route('notifications.index'));
    }

    public function readAll(Request $request)
    {
        $request->user()->unreadNotifications->markAsRead();

        return back();
    }
}

paginate() keeps ?filter=unread on every page link because the view calls withQueryString().

Live, with Livewire

As above, the bell is right when the page is drawn, and Mark all as read is a form; the tick on a row dispatches read and nothing answers it. Wrap the bell in a Livewire component to answer it, and to keep the count fresh:

namespace App\Livewire;

use Livewire\Component;

class NotificationBell extends Component
{
    public function markAsRead(string $id): void
    {
        auth()->user()->notifications()->whereKey($id)->first()?->markAsRead();
    }

    public function markAllAsRead(): void
    {
        auth()->user()->unreadNotifications->markAsRead();
    }

    public function render()
    {
        $user = auth()->user();

        return view('livewire.notification-bell', [
            'notifications' => $user->notifications()->latest()->limit(8)->get(),
            'unread' => $user->unreadNotifications()->count(),
        ]);
    }
}
{{-- resources/views/livewire/notification-bell.blade.php --}}
<div
    wire:poll.30s.visible
    x-on:read="$wire.markAsRead($event.detail.id)"
    x-on:submit="if ($event.target.action === @js(route('notifications.read-all'))) { $event.preventDefault(); $wire.markAllAsRead() }"
>
    <x-notification-bell :notifications="$notifications" :unread="$unread" />
</div>

Then the layout draws <livewire:notification-bell /> where it drew <x-notification-bell … />, and the view composer no longer needs unreadCount and latestNotifications.

  • wire:poll.30s.visible asks every 30 seconds while the tab is in view, so the badge and the list catch up without a reload. For new ones the moment they arrive, listen for a broadcast instead (#[On('echo-private:App.Models.User.{userId},.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated')] on a method that does nothing; the re-render is the point).
  • The tick and Mark all as read change the rows in place. The Mark all as read form still posts if the script is not there; the submit handler takes over only that form, so Accept and Decline still post.
  • The rows carry wire:key, so a poll that adds one at the top does not redraw the rest.

Phone, keyboard, no script

  • Phone: below lg the bell opens a drawer from the right, drawn only while open, so the list is not on the page twice. The drawer is named "Notifications" but given no title, as the list draws its own heading with the count and Mark all as read, so its top bar holds only the close button.
  • Keyboard: the popover opens from the bell with Enter or Space, and Escape closes it with focus back on the bell; Tab moves through each row's link, its actions and its tick in turn. The drawer holds focus while open.
  • No script: the popover, the drawer and the tick need Alpine and the package's script, so without one the bell is a link to the notifications page instead (a third bell, drawn only when scripting is off). That page needs neither: its tabs, rows, Mark all as read, Accept and Decline are links and forms.

From the package repo: edit this page on GitHub.

Was this page helpful?