You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.

Query String

Be amazing at Livewire
with our in-depth screencasts.
Watch Now

Introduction

Sometimes it's useful to update the browser's query string when your component state changes.

For example, if you were building a "search posts" component, and wanted the query string to reflect the current search value like so:

https://your-app.com/search-posts?search=some-search-string

This way, when a user hits the back button, or bookmarks the page, you can get the initial state out of the query string, rather than resetting the component every time.

In these cases, you can add a property's name to protected $queryString, and Livewire will update the query string every time the property value changes, and also update the property when the query string changes.

            
1class SearchPosts extends Component
2{
3 public $search;
4 
5 protected $queryString = ['search'];
6 
7 public function render()
8 {
9 return view('livewire.search-posts', [
10 'posts' => Post::where('title', 'like', '%'.$this->search.'%')->get(),
11 ]);
12 }
13}
            
1<div>
2 <input wire:model="search" type="search" placeholder="Search posts by title...">
3 
4 <h1>Search Results:</h1>
5 
6 <ul>
7 @foreach($posts as $post)
8 <li>{{ $post->title }}</li>
9 @endforeach
10 </ul>
11</div>

Keeping A Clean Query String

In the case above, when the search property is empty, the query string will look like this:

?search=

There are other cases where you might want to only represent a value in the query string if it is NOT the default setting.

For example, if you have a $page property to track pagination in a component, you may want to remove the page property from the query string when the user is on the first page.

In cases like these, you can use the following syntax:

            
1class SearchPosts extends Component
2{
3 public $foo;
4 public $search = '';
5 public $page = 1;
6 
7 protected $queryString = [
8 'foo',
9 'search' => ['except' => ''],
10 'page' => ['except' => 1],
11 ];
12 
13 ...
14}

Query String Aliases

Additionally, if you want to modify how properties are represented in the URL, Livewire offers a simple syntax for aliasing query strings.

For example, if you want to shorten the URL, where the page property is represented as p and search as s, you can use the as modifier to achieve that outcome.

            
1class SearchPosts extends Component
2{
3 public $search = '';
4 public $page = 1;
5 
6 protected $queryString = [
7 'search' => ['except' => '', 'as' => 's'],
8 'page' => ['except' => 1, 'as' => 'p'],
9 ];
10 
11 ...
12}

Now the URL can look like this:

?s=Livewire%20is%20awesome&p=2

← Previous Topic File Downloads
Next Topic → Authorization