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.

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.
Interested in more posts ?
Here are some other posts you might be interested in.

Secure your Laravel application with Google reCAPTCHA. add reCAPTCHA to your for...

This document describes the structure and components of the main Blade layout fi...
Want more ?
View all the posts.