Insights & Tutorials

Custom unsaved changes alert in filamentphp

If you want to add a custom alert to prevent the user from exiting the page accidently, in this article we will tackle exactly how in filamentphp.

Custom unsaved changes alert in filamentphp's cover image

First here is the code

//prevent-page-leave-alert.blade.php

@php
    use Filament\Support\Facades\FilamentView;
@endphp

@if (FilamentView::hasSpaMode())
    @script
    <script>
        shouldPreventNavigation = () => {
            if ($wire?.__instance?.effects?.redirect) {
                return
            }

            return $wire.preventPageLeave
        }

        const showUnsavedChangesAlert = () => {
            return confirm(@js(__('filament-panels::unsaved-changes-alert.body')))
        }

        document.addEventListener('livewire:navigate', (event) => {
            if (typeof @this !== 'undefined') {
                if (!shouldPreventNavigation()) {
                    return
                }

                if (showUnsavedChangesAlert()) {
                    return
                }

                event.preventDefault()
            }
        })

        window.addEventListener('beforeunload', (event) => {
            if (!shouldPreventNavigation()) {
                return
            }

            event.preventDefault()
            event.returnValue = true
        })
    </script>
    @endscript
@else
    @script
    <script>
        window.addEventListener('beforeunload', (event) => {
            if (! $wire.preventPageLeave) {
                return
            }

            event.preventDefault()
            event.returnValue = true
        })
    </script>
    @endscript
@endif

    

plus in your custom pages you need to use the following property

public bool $preventPageLeave = false;

it is false by default because we want the user to navigate freely until we have some action running that we want to keep, then we set the variable to true and the user will be prompted if they wanted to quit.

But why didn't we use HasUnsavedDataChangesAlert trait and the <x-filament-panels::page.unsaved-data-changes-alert /> blade component ?

Well, good question. it is because these two necessitate the page to have a $data property that not all custom pages would have.

Start your project journey with me today!

I'm a software developer, I love building web applications and solve problems. I'm always looking for new challenges and opportunities to learn and grow.

Book a meet

Let's start your project journey together.

You can contact me anytime on

©2025 Abdelhamid Errahmouni, All rights reserved.