Courses

Livewire 3 for Beginners with Laravel 12 Starter Kit

SPA with wire:navigate

Summary of this lesson:
- Enabling SPA experience with `wire:navigate` in Livewire v3
- Updating page content without a full reload
- Reloading scripts with `data-navigate-track` when needed

These days, many applications are built as single-page applications (SPA). Livewire v3 offers this experience, with wire:navigate syntax.

It is heavily used in the Livewire Starter Kit, which we will cover in the next section, so here's a quick lesson for you to understand the wire:navigate.


Basic Usage

To use this feature, you just need to add a wire:navigate directive to the navigation links. For example, if we have a couple of routes.

Route::get('posts', \App\Livewire\ShowPosts::class);
Route::get('posts/create', \App\Livewire\CreatePost::class);
Route::get('users', \App\Livewire\ShowUsers::class);

Then we add wire:navigate to each link.

<nav>
<a href="/posts" wire:navigate>Posts</a>
<a href="/posts/create" wire:navigate>Create Post</a>
<a href="/users" wire:navigate>Users</a>
</nav>

After clicking a link, Livewire will load the new page in the background, and only then will it replace <title> and <body> content with the new one.

While a new page is loading, Livewire will show the loading indicator at the top. You can configure this setting in the config/livewire.php by changing the navigate.show_progress_bar value.

When redirecting to other pages, for example, after creating a post to the posts list page, to have a SPA experience, you need to provide a navigate argument to the redirect method.

return $this->redirect('/posts', navigate: true);

Reloading Scripts in Header

By default, Livewire won't reload the whole <head> section. It's a common practice to add scripts with a hash version so that the browser would always use the newest file instead of a cached old one.

For Livewire to reload the <script> tag, you need to add a data-navigate-track.

<head>
<script src="/app.js?id=123" data-navigate-track></script>
</head>

If you use Laravel's Vite plugin for building assets, you don't need to do anything. Livewire automatically will add the data-navigate-track.

<head>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

You can learn more about wire:navigate in the official documentation.


Ok, after a few quick lessons about multi-component and multi-page structure, let's dive into a new practical section: trying out the Laravel 12 Livewire Starter Kit and creating a CRUD on top of it.

Previous: Multiple Components and Events

No comments yet…

avatar
You can use Markdown