URLクエリパラメータ
Livewireを使用すると、コンポーネントのプロパティをURLのクエリ文字列に保存できます。たとえば、コンポーネント内の $search
プロパティをURLに含めたい場合があります: https://example.com/users?search=bob
。これは、フィルタリング、ソート、ページネーションなどの場合に特に役立ちます。ユーザーがページの特定の状態を共有したり、ブックマークしたりできるようになります。Livewire allows you to store component properties in the URL's query string. For example, you may want a $search
property in your component to be included in the URL: https://example.com/users?search=bob
. This is particularly useful for things like filtering, sorting, and pagination, as it allows users to share and bookmark specific states of a page.
基本的な使い方Basic usage
以下は、単純なテキスト入力を使用してユーザーを名前で検索できる ShowUsers
コンポーネントです。Below is a ShowUsers
component that allows you to search users by their name via a simple text input:
<?php
namespace App\Livewire;
use Livewire\Attributes\Url;
use Livewire\Component;
use App\Models\User;
class ShowUsers extends Component
{
public $search = '';
public function render()
{
return view('livewire.show-users', [
'users' => User::search($this->search)->get(),
]);
}
}
<div>
<input type="text" wire:model.live="search">
<ul>
@foreach ($users as $user)
<li wire:key="{{ $user->id }}">{{ $user->name }}</li>
@endforeach
</ul>
</div>
ご覧のとおり、テキスト入力で wire:model.live="search"
を使用しているため、ユーザーがフィールドに入力すると、ネットワークリクエストが送信され、 $search
プロパティが更新され、フィルタリングされたユーザーのセットがページに表示されます。As you can see, because the text input uses wire:model.live="search"
, as a user types into the field, network requests will be sent to update the $search
property and show a filtered set of users on the page.
ただし、訪問者がページをリフレッシュすると、検索値と結果は失われます。However, if the visitor refreshes the page, the search value and results will be lost.
訪問者がページをリフレッシュしたり、URLを共有したりできるように、検索値をページロード間で保持するには、次のように $search
プロパティの上に #[Url]
アトリビュートを追加して、検索値をURLのクエリ文字列に保存できます。To preserve the search value across page loads so that a visitor can refresh the page or share the URL, we can store the search value in the URL's query string by adding the #[Url]
attribute above the $search
property like so:
<?php
namespace App\Livewire;
use Livewire\Attributes\Url;
use Livewire\Component;
use App\Models\User;
class ShowUsers extends Component
{
#[Url] // [tl! highlight]
public $search = '';
public function render()
{
return view('livewire.show-users', [
'posts' => User::search($this->search)->get(),
]);
}
}
これで、ユーザーが検索フィールドに「bob」と入力すると、ブラウザのURLバーに次のように表示されます。Now, if a user types "bob" into the search field, the URL bar in the browser will show:
https://example.com/users?search=bob
このURLを新しいブラウザウィンドウからロードすると、「bob」が検索フィールドに入力され、ユーザーの結果がそれに応じてフィルタリングされます。If they now load this URL from a new browser window, "bob" will be filled in the search field, and the user results will be filtered accordingly.
URLからのプロパティの初期化Initializing properties from the URL
前の例で見たように、プロパティが #[Url]
を使用している場合、URLのクエリ文字列に更新された値を保存するだけでなく、ページロード時に既存のクエリ文字列値も参照します。As you saw in the previous example, when a property uses #[Url]
, not only does it store its updated value in the query string of the URL, it also references any existing query string values on page load.
たとえば、ユーザーがURL https://example.com/users?search=bob
にアクセスすると、Livewireは $search
の初期値を「bob」に設定します。For example, if a user visits the URL https://example.com/users?search=bob
, Livewire will set the initial value of $search
to "bob".
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url]
public $search = ''; // "bob"に設定されます...
// ...
}
NullableなプロパティNullable properties
デフォルトでは、?search=
のように空のクエリ文字列エントリを含むページがロードされた場合、Livewireはその値を空の文字列として扱います。多くの場合、これは予想される動作ですが、?search=
を null
として扱いたい場合があります。By default, if a page is loaded with an empty query string entry like ?search=
, Livewire will treat that value as an empty string. In many cases, this is expected, however there are times when you want ?search=
to be treated as null
.
このような場合は、次のようにnullableな型ヒントを使用できます。In these cases, you can use a nullable typehint like so:
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url]
public ?string $search; // [tl! highlight]
// ...
}
上記の型ヒントに ?
が存在するため、Livewireは ?search=
を認識し、 $search
を空の文字列ではなく null
に設定します。Because ?
is present in the above typehint, Livewire will see ?search=
and set $search
to null
instead of an empty string.
これは逆の場合も同様で、アプリケーションで $this->search = null
を設定すると、クエリ文字列に ?search=
として表示されます。This works the other way around as well, if you set $this->search = null
in your application, it will be represented in the query string as ?search=
.
エイリアスの使用Using an alias
Livewireを使用すると、URLのクエリ文字列に表示される名前を完全に制御できます。たとえば、$search
プロパティがある場合に、実際のプロパティ名を難読化したり、q
に短縮したりしたい場合があります。Livewire gives you full control over what name displays in the URL's query string. For example, you may have a $search
property but want to either obfuscate the actual property name or shorten it to q
.
#[Url]
アトリビュートに as
パラメータを指定することで、クエリ文字列エイリアスを指定できます。You can specify a query string alias by providing the as
parameter to the #[Url]
attribute:
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url(as: 'q')]
public $search = '';
// ...
}
これで、ユーザーが検索フィールドに「bob」と入力すると、URLには ?search=bob
ではなく https://example.com/users?q=bob
が表示されます。Now, when a user types "bob" into the search field, the URL will show: https://example.com/users?q=bob
instead of ?search=bob
.
特定の値の除外Excluding certain values
デフォルトでは、Livewireは、値が初期化時から変更された場合にのみ、クエリ文字列にエントリを配置します。ほとんどの場合、これは望ましい動作ですが、Livewireがクエリ文字列から除外する値をより細かく制御したいシナリオがあります。このような場合は、 except
パラメータを使用できます。By default, Livewire will only put an entry in the query string when it's value has changed from what it was at initialization. Most of the time, this is the desired behavior, however, there are certain scenarios where you may want more control over which value Livewire excludes from the query string. In these cases you can use the except
parameter.
たとえば、以下のコンポーネントでは、 $search
の初期値が mount()
で変更されています。search
の値が空の文字列の場合にのみ、ブラウザがクエリ文字列から search
を除外するようにするには、 except
パラメータが #[Url]
に追加されています。For example, in the component below, the initial value of $search
is modified in mount()
. To ensure the browser will only ever exclude search
from the query string if the search
value is an empty string, the except
parameter has been added to #[Url]
:
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url(except: '')]
public $search = '';
public function mount() {
$this->search = auth()->user()->username;
}
// ...
}
上記の例で except
がない場合、Livewireは search
の値が auth()->user()->username
の初期値と等しい場合は常に、クエリ文字列から search
エントリを削除します。代わりに、 except: ''
が使用されているため、Livewireは search
が空の文字列の場合を除き、すべてのクエリ文字列値を保持します。Without except
in the above example, Livewire would remove the search
entry from the query string any time the value of search
is equal to the initial value of auth()->user()->username
. Instead, because except: ''
has been used, Livewire will preserve all query string values except when search
is an empty string.
ページロード時の表示Display on page load
デフォルトでは、Livewireはページで値が変更された後にのみ、クエリ文字列に値を表示します。たとえば、 $search
のデフォルト値が空の文字列 ""
の場合、実際の検索入力が空の場合、URLに値は表示されません。By default, Livewire will only display a value in the query string after the value has been changed on the page. For example, if the default value for $search
is an empty string: ""
, when the actual search input is empty, no value will appear in the URL.
値が空の場合でも、?search
エントリを常にクエリ文字列に含める場合は、 #[Url]
アトリビュートに keep
パラメータを指定できます。If you want the ?search
entry to always be included in the query string, even when the value is empty, you can provide the keep
parameter to the #[Url]
attribute:
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url(keep: true)]
public $search = '';
// ...
}
これで、ページがロードされると、URLは次のように変更されます: https://example.com/users?search=
Now, when the page loads, the URL will be changed to the following: https://example.com/users?search=
履歴への保存Storing in history
デフォルトでは、Livewireは history.pushState()
の代わりに history.replaceState()
を使用してURLを変更します。これは、Livewireがクエリ文字列を更新するときに、ブラウザの履歴状態に新しいエントリを追加するのではなく、現在のエントリを変更することを意味します。By default, Livewire uses history.replaceState()
[https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState] to modify the URL instead of history.pushState()
[https://developer.mozilla.org/en-US/docs/Web/API/History/pushState]. This means that when Livewire updates the query string, it modifies the current entry in the browser's history state instead of adding a new one.
Livewireは現在の履歴を「置き換える」ため、ブラウザの「戻る」ボタンを押すと、以前の ?search=
値ではなく、前のページに戻ります。Because Livewire "replaces" the current history, pressing the "back" button in the browser will go to the previous page rather than the previous ?search=
value.
URLを更新するときにLivewireに history.pushState
を強制的に使用させるには、 #[Url]
アトリビュートに history
パラメータを指定します。To force Livewire to use history.pushState
when updating the URL, you can provide the history
parameter to the #[Url]
attribute:
use Livewire\Attributes\Url;
use Livewire\Component;
class ShowUsers extends Component
{
#[Url(history: true)]
public $search = '';
// ...
}
上記の例では、ユーザーが検索値を「bob」から「frank」に変更し、ブラウザの戻るボタンをクリックすると、検索値(およびURL)は、以前にアクセスしたページに移動するのではなく、「bob」に戻ります。In the example above, when a user changes the search value from "bob" to "frank" and then clicks the browser's back button, the search value (and the URL) will be set back to "bob" instead of navigating to the previously visited page.
queryStringメソッドの使用Using the queryString method
クエリ文字列は、コンポーネントのメソッドとして定義することもできます。これは、一部のプロパティに動的なオプションがある場合に役立ちます。The query string can also be defined as a method on the component. This can be useful if some properties have dynamic options.
use Livewire\Component;
class ShowUsers extends Component
{
// ...
protected function queryString()
{
return [
'search' => [
'as' => 'q',
],
];
}
}
TraitのフックTrait hooks
Livewireは、クエリ文字列のフックも提供しています。Livewire offers hooks[/docs/lifecycle-hooks] for query strings as well.
trait WithSorting
{
// ...
protected function queryStringWithSorting()
{
return [
'sortBy' => ['as' => 'sort'],
'sortDirection' => ['as' => 'direction'],
];
}
}