Improved handling of 404 errors with Livewire

Published at Feb 11, 2024

Sponsored by

unolia.com

All your domains in one place. Helps you find problems, gives you performance and security insights!


Want to sponsor this blog ? Contact me or use Github sponsor

I like to use the findOrFail() function in Livewire methods that call actions. But I really don't like the default behaviour of Livewire showing a modal view with a 404. Let me show you how to personalise that.

This is a short solution, simply copy this code into your app.js (or in a <script> tag if you want different behaviour through your app) and customize it with a modal or notification for your user. What makes the most sense for your application.

Since I'm using it in a CRUD context here, here is a simple and effective code.

Copied!
document.addEventListener('livewire:init', () => {
Livewire.hook('request', ({ fail }) => {
fail(({ status, preventDefault }) => {
if (status === 404) {
// Your preferred behaviour
if (confirm('Ressource not found. Reload the page maybe?')) {
window.location.reload()
}
 
// Prevent Livewire default behaviour
preventDefault()
}
})
})
})

And that's basically it! If you wanna learn more on the subject, checkout the Livewire documentation on Javascript hooks

As a little bonus/advanced way, here's how you can recharge just the component instead. I don't guarantee this will work in all applications, as it is a hacky way to access the Livewire request payload. Livewire can send multiple commands at once and this code may not access the correct one. This works for a full-page component with a method call, but it's a risky method and can break with a Livewire update.

Copied!
if (confirm('Ressource not found. Reload the component maybe?')) {
let object = JSON.parse(payload);
let snapshot = JSON.parse(object.components[0].snapshot);
let component = Livewire.find(snapshot.memo.id);
component.$refresh();
}

Have a nice day!

#livewire #laravel #javascript

Syntax highlighting provided by torchlight.dev