Home Projects Portfolio Dashboard Export PDF Log in

Optimizing Database Notifications in Filament and Laravel

Introduction

In our devlog-ist/landing project, we recently tackled a challenge involving Filament's notification system. Specifically, we needed to properly display database-backed notifications in the Filament UI while implementing a secure, "delete-on-click" interaction model.

The Notification Schema Challenge

Filament's notification bell expects specific keys to render content. Our custom notification classes were storing data in a way that wasn't mapped to the expected fields, resulting in empty notifications. To fix this, we updated our toArray() method to provide the necessary metadata while keeping our custom logic for backward compatibility.

public function toArray($notifiable): array
{
    return [
        'title' => 'Important Update',
        'body' => 'You have a new activity to review.',
        'icon' => 'heroicon-o-bell',
        'iconColor' => 'primary',
        'actions' => [ /* Action details */ ],
        'custom_meta' => $this->metaData,
    ];
}

By mapping our internal fields to the expected keys like title and body, we ensure the notification center can parse and display the UI elements correctly without sacrificing our original data structure.

Secure Notification Handling

We also introduced a dedicated endpoint for notification interactions. Instead of linking directly to a target, we route through an invokable controller. This provides two key benefits: open-redirect protection via domain validation and automatic notification cleanup.

public function __invoke(Request $request)
{
    $target = $request->query('target');
    
    if (!$this->isInternal($target)) {
        abort(403);
    }

    auth()->user()->unreadNotifications()->oldest()->first()?->delete();

    return redirect($target);
}

This controller acts as a gatekeeper. It identifies the oldest unread notification for the current user, removes it from the database upon interaction, and then redirects the user to the destination, ensuring our database remains tidy.

Quality Assurance

To ensure stability, we implemented regression tests covering unauthenticated access, cross-user isolation, and URL validation. These tests verify that the system remains secure and that notifications are handled reliably even as the volume of system alerts grows.

Takeaway

When working with third-party UI packages like Filament, always ensure your data objects explicitly map to the interface requirements of the component. Use a centralized controller for your notification interactions to keep your business logic secure and your database clean.


Generated with Gitvlg.com

Optimizing Database Notifications in Filament and Laravel
Germanwithpants

Germanwithpants

Author

Share: