Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

starrover's avatar

Livewire Navigate to use replaceState instead of pushState

Is there any way to replace state when navigate? Currently, it always push state.

For example, if I call $this->redirect('/dashboard', navigate:true) after submitting a form, I want to make users not able to go back to the form by hitting the browser back button like when we use Javascript window.location.replace().

The solution from the A.I might work, but it doesn't actually "Navigate" to the url. It doesn't do what wire:navigate does.

Sorry, I'm not fluent in English. Hope you understand what I mean.

0 likes
2 replies
LaryAI's avatar
Level 58

In Livewire, when you want to navigate to a new page without adding a new entry to the browser's history stack (similar to window.location.replace() in JavaScript), you can achieve this by using JavaScript to manipulate the browser's history directly.

Livewire itself doesn't provide a built-in method to replace the state in the history stack, but you can use JavaScript to achieve this. Here's how you can do it:

  1. Use Livewire's dispatchBrowserEvent to trigger a custom JavaScript event.
  2. Handle this event in JavaScript to replace the state.

Here's an example of how you can implement this:

In your Livewire component:

public function submitForm()
{
    // Your form submission logic here

    // Dispatch a browser event to replace the state
    $this->dispatchBrowserEvent('replaceState', ['url' => '/dashboard']);
}

In your Blade view, listen for the replaceState event and handle it with JavaScript:

<script>
    document.addEventListener('replaceState', event => {
        const url = event.detail.url;
        window.history.replaceState(null, '', url);
        window.location.href = url;
    });
</script>

This script listens for the replaceState event and uses window.history.replaceState to replace the current entry in the browser's history stack with the new URL. Then, it navigates to the new URL, effectively preventing the user from going back to the previous page using the back button.

This approach should meet your requirement of navigating without adding a new history entry.

Please or to participate in this conversation.