wire:model
Livewire を使うと、wire:model
を使ってコンポーネントのプロパティの値をフォーム入力と簡単にバインドできます。Livewire makes it easy to bind a component property's value with form inputs using wire:model
.
以下は、wire:model
を使用して、"Create Post" コンポーネントで $title
および $content
プロパティをフォーム入力とバインドする簡単な例です。Here is a simple example of using wire:model
to bind the $title
and $content
properties with form inputs in a "Create Post" component:
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
$post = Post::create([
'title' => $this->title
'content' => $this->content
]);
// ...
}
}
<form wire:submit="save">
<label>
<span>Title</span>
<input type="text" wire:model="title"> <!-- [tl! highlight] -->
</label>
<label>
<span>Content</span>
<textarea wire:model="content"></textarea> <!-- [tl! highlight] -->
</label>
<button type="submit">Save</button>
</form>
両方の入力が wire:model
を使用しているため、「Save」ボタンが押されると、それらの値はサーバのプロパティと同期されます。Because both inputs use wire:model
, their values will be synchronized with the server's properties when the "Save" button is pressed.
Warning! "なぜ入力してもコンポーネントがライブアップデートしないのですか?" ブラウザでこれを試して、タイトルが自動的に更新されない理由がわからない場合は、Livewire はユーザーがフィールドに入力するときではなく、submit ボタンを押すなど、「アクション」が送信されたときにのみコンポーネントを更新するためです。これにより、ネットワークリクエストが削減され、パフォーマンスが向上します。ユーザーが入力するときに「ライブ」更新を有効にするには、代わりに
wire:model.live
を使用できます。データバインディングの詳細はこちら。[!warning] "Why isn't my component live updating as I type?" If you tried this in your browser and are confused why the title isn't automatically updating, it's because Livewire only updates a component when an "action" is submitted—like pressing a submit button—not when a user types into a field. This cuts down on network requests and improves performance. To enable "live" updating as a user types, you can usewire:model.live
instead. Learn more about data binding[/docs/properties#data-binding].
更新タイミングのカスタマイズCustomizing update timing
デフォルトでは、Livewire はアクションが実行されたとき(wire:click
や wire:submit
など)にのみネットワークリクエストを送信し、wire:model
入力が更新されたときは送信しません。By default, Livewire will only send a network request when an action is performed (like wire:click
or wire:submit
), NOT when a wire:model
input is updated.
これにより、ネットワークリクエストが削減され、ユーザーのエクスペリエンスが向上するため、Livewire のパフォーマンスが大幅に向上します。This drastically improves the performance of Livewire by reducing network requests and provides a smoother experience for your users.
ただし、リアルタイム検証など、サーバをより頻繁に更新したい場合があります。However, there are occasions where you may want to update the server more frequently for things like real-time validation.
ライブ更新Live updating
ユーザーが入力フィールドに入力するときにプロパティの更新をサーバに送信するには、wire:model
に .live
修飾子を追加します。To send property updates to the server as a user types into an input-field, you can append the .live
modifier to wire:model
:
<input type="text" wire:model.live="title">
デバウンスのカスタマイズCustomizing the debounce
デフォルトでは、wire:model.live
を使用すると、Livewire はサーバの更新に 150 ミリ秒のデバウンスを追加します。これは、ユーザーが継続的に入力している場合、Livewire はリクエストを送信する前に、ユーザーが 150 ミリ秒間入力を停止するまで待機することを意味します。By default, when using wire:model.live
, Livewire adds a 150 millisecond debounce to server updates. This means if a user is continually typing, Livewire will wait until the user stops typing for 150 milliseconds before sending a request.
このタイミングをカスタマイズするには、.debounce.Xms
を入力に追加します。以下は、デバウンスを 250 ミリ秒に変更する例です。You can customize this timing by appending .debounce.Xms
to the input. Here is an example of changing the debounce to 250 milliseconds:
<input type="text" wire:model.live.debounce.250ms="title">
「blur」イベントでの更新Updating on "blur" event
.blur
修飾子を追加すると、Livewire はユーザーが入力からクリックして離れたり、Tab キーを押して次の入力に移動したりしたときにのみ、プロパティの更新を含むネットワークリクエストを送信します。By appending the .blur
modifier, Livewire will only send network requests with property updates when a user clicks away from an input, or presses the tab key to move to the next input.
.blur
を追加すると、サーバの更新頻度を高めたいが、ユーザーが入力するときには更新したくないシナリオに役立ちます。たとえば、リアルタイム検証は .blur
が役立つ一般的なインスタンスです。Adding .blur
is helpful for scenarios where you want to update the server more frequently, but not as a user types. For example, real-time validation is a common instance where .blur
is helpful.
<input type="text" wire:model.blur="title">
「change」イベントでの更新Updating on "change" event
.blur
の動作が正確に必要とするものではなく、代わりに .change
が必要な場合があります。There are times when the behavior of .blur
isn't exactly what you want and instead .change
is.
たとえば、select 入力が変更されるたびに検証を実行する場合、.change
を追加すると、Livewire はネットワークリクエストを送信し、ユーザーが新しいオプションを選択するとすぐにプロパティを検証します。これは、ユーザーが select 入力から Tab キーを押して離れた後にのみサーバを更新する .blur
とは対照的です。For example, if you want to run validation every time a select input is changed, by adding .change
, Livewire will send a network request and validate the property as soon as a user selects a new option. As opposed to .blur
which will only update the server after the user tabs away from the select input.
<select wire:model.change="title">
<!-- ... -->
</select>
テキスト入力に加えられた変更は、Livewire コンポーネントの $title
プロパティと自動的に同期されます。Any changes made to the text input will be automatically synchronized with the $title
property in your Livewire component.
利用可能なすべての修飾子All available modifiers
修飾子Modifier | 説明Description |
---|---|
.live .live |
ユーザーが入力するときに更新を送信しますSend updates as a user types |
.blur .blur |
blur イベントでのみ更新を送信しますOnly send updates on the blur event |
.change .change |
change イベントでのみ更新を送信しますOnly send updates on the the change event |
.lazy .lazy |
.change のエイリアスAn alias for .change |
.debounce.[?]ms .debounce.[?]ms |
指定されたミリ秒の遅延で更新の送信をデバウンスしますDebounce the sending of updates by the specified millisecond delay |
.throttle.[?]ms .throttle.[?]ms |
指定されたミリ秒間隔でネットワークリクエストの更新をスロットルしますThrottle network request updates by the specified millisecond interval |
.number .number |
入力のテキスト値をサーバ上の int にキャストしますCast the text value of an input to int on the server |
.boolean .boolean |
入力のテキスト値をサーバ上の bool にキャストしますCast the text value of an input to bool on the server |
.fill .fill |
ページロード時に "value" HTML 属性によって提供される初期値を使用しますUse the initial value provided by a "value" HTML attribute on page-load |
入力フィールドInput fields
Livewire は、ほとんどのネイティブ入力要素をすぐにサポートしています。つまり、ブラウザの任意の入力要素に wire:model
をアタッチして、プロパティをそれらに簡単にバインドできるはずです。Livewire supports most native input elements out of the box. Meaning you should just be able to attach wire:model
to any input element in the browser and easily bind properties to them.
以下は、利用可能なさまざまな入力タイプと、Livewire コンテキストでのそれらの使用方法をまとめた包括的なリストです。Here's a comprehensive list of the different available input types and how you use them in a Livewire context.
テキスト入力Text inputs
まず第一に、テキスト入力はほとんどのフォームの基盤です。以下は、「title」という名前のプロパティをテキスト入力にバインドする方法です。First and foremost, text inputs are the bedrock of most forms. Here's how to bind a property named "title" to one:
<input type="text" wire:model="title">
テキストエリア入力Textarea inputs
Textarea 要素も同様に簡単です。textarea に wire:model
を追加するだけで、値がバインドされます。Textarea elements are similarly straightforward. Simply add wire:model
to a textarea and the value will be bound:
<textarea type="text" wire:model="content"></textarea>
「content」の値が文字列で初期化されている場合、Livewire は textarea にその値を入力します。以下のようなことを行う必要はありません。If the "content" value is initialized with a string, Livewire will fill the textarea with that value - there's no need to do something like the following:
<!-- 警告:このスニペットは、すべきでないことを示しています... -->
<textarea type="text" wire:model="content">{{ $content }}</textarea>
チェックボックスCheckboxes
チェックボックスは、ブール値プロパティを切り替える場合など、単一の値に使用できます。または、チェックボックスを使用して、関連する値のグループ内の単一の値を切り替えることもできます。両方のシナリオについて説明します。Checkboxes can be used for single values, such as when toggling a boolean property. Or, checkboxes may be used to toggle a single value in a group of related values. We'll discuss both scenarios:
単一のチェックボックスSingle checkbox
サインアップフォームの最後に、ユーザーがメールの更新にオプトインできるチェックボックスが表示される場合があります。このプロパティを $receiveUpdates
と呼ぶことができます。wire:model
を使用して、この値をチェックボックスに簡単にバインドできます。At the end of a signup form, you might have a checkbox allowing the user to opt-in to email updates. You might call this property $receiveUpdates
. You can easily bind this value to the checkbox using wire:model
:
<input type="checkbox" wire:model="receiveUpdates">
これで、$receiveUpdates
値が false
の場合、チェックボックスはオフになります。もちろん、値が true
の場合、チェックボックスはオンになります。Now when the $receiveUpdates
value is false
, the checkbox will be unchecked. Of course, when the value is true
, the checkbox will be checked.
複数のチェックボックスMultiple checkboxes
次に、ユーザーが更新を受信するかどうかを決定できることに加えて、クラスに $updateTypes
という配列プロパティがあり、ユーザーがさまざまな更新タイプから選択できるとします。Now, let's say in addition to allowing the user to decide to receive updates, you have an array property in your class called $updateTypes
, allowing the user to choose from a variety of update types:
public $updateTypes = [];
複数のチェックボックスを $updateTypes
プロパティにバインドすることにより、ユーザーは複数の更新タイプを選択でき、それらは $updateTypes
配列プロパティに追加されます。By binding multiple checkboxes to the $updateTypes
property, the user can select multiple update types and they will be added to the $updateTypes
array property:
<input type="checkbox" value="email" wire:model="updateTypes">
<input type="checkbox" value="sms" wire:model="updateTypes">
<input type="checkbox" value="notification" wire:model="updateTypes">
たとえば、ユーザーが最初の 2 つのボックスをオンにし、3 番目のボックスをオンにしない場合、$updateTypes
の値は ["email", "sms"]
になります。For example, if the user checks the first two boxes but not the third, the value of $updateTypes
will be: ["email", "sms"]
ラジオボタンRadio buttons
単一のプロパティの 2 つの異なる値を切り替えるには、ラジオボタンを使用できます。To toggle between two different values for a single property, you may use radio buttons:
<input type="radio" value="yes" wire:model="receiveUpdates">
<input type="radio" value="no" wire:model="receiveUpdates">
セレクトドロップダウンSelect dropdowns
Livewire を使用すると、<select>
ドロップダウンを簡単に操作できます。ドロップダウンに wire:model
を追加すると、現在選択されている値が、指定されたプロパティ名にバインドされ、その逆も同様です。Livewire makes it simple to work with <select>
dropdowns. When adding wire:model
to a dropdown, the currently selected value will be bound to the provided property name and vice versa.
さらに、選択されるオプションに手動で selected
を追加する必要はありません。Livewire が自動的に処理します。In addition, there's no need to manually add selected
to the option that will be selected - Livewire handles that for you automatically.
以下は、静的な都道府県のリストで埋められたセレクトドロップダウンの例です。Below is an example of a select dropdown filled with a static list of states:
<select wire:model="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
...
</select>
特定の都道府県が選択されている場合(たとえば、「Alaska」)、コンポーネントの $state
プロパティは AK
に設定されます。値を「AK」ではなく「Alaska」に設定する場合は、<option>
要素から value=""
属性を完全に省略できます。When a specific state is selected, for example, "Alaska", the $state
property on the component will be set to AK
. If you would prefer the value to be set to "Alaska" instead of "AK", you can leave the value=""
attribute off the <option>
element entirely.
多くの場合、Blade を使用してドロップダウンオプションを動的に構築します。Often, you may build your dropdown options dynamically using Blade:
<select wire:model="state">
@foreach (\App\Models\State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
デフォルトで特定のオプションが選択されていない場合は、「都道府県を選択...」などのミュートされたプレースホルダーオプションをデフォルトで表示することができます。If you don't have a specific option selected by default, you may want to show a muted placeholder option by default, such as "Select a state":
<select wire:model="state">
<option disabled value="">都道府県を選択...</option>
@foreach (\App\Models\State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
ご覧のとおり、テキスト入力のように select メニューには「placeholder」属性はありません。代わりに、リストの最初のオプションとして disabled
オプション要素を追加する必要があります。As you can see, there is no "placeholder" attribute for a select menu like there is for text inputs. Instead, you have to add a disabled
option element as the first option in the list.
依存セレクトドロップダウンDependent select dropdowns
場合によっては、ある select メニューを別の select メニューに依存させたい場合があります。たとえば、選択した都道府県に基づいて変化する都市のリストなどです。Sometimes you may want one select menu to be dependent on another. For example, a list of cities that changes based on which state is selected.
ほとんどの場合、これは期待どおりに機能しますが、重要な注意点が 1 つあります。変更する select に wire:key
を追加して、オプションが変更されたときに Livewire がその値を正しく更新するようにする必要があります。For the most part, this works as you'd expect, however there is one important gotcha: You must add a wire:key
to the changing select so that Livewire properly refreshes its value when the options change.
以下は、都道府県と都市の 2 つの select の例です。都道府県の select が変更されると、都市の select のオプションが適切に変更されます。Here's an example of two selects, one for states, one for cities. When the state select changes, the options in the city select will change properly:
<!-- States select menu... -->
<select wire:model.live="selectedState">
@foreach (State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
<!-- Cities dependent select menu... -->
<select wire:model.live="selectedCity" wire:key="{{ $selectedState }}"> <!-- [tl! highlight] -->
@foreach (City::whereStateId($selectedState->id)->get() as $city)
<option value="{{ $city->id }}">{{ $city->label }}</option>
@endforeach
</select>
繰り返しますが、ここで標準でないのは、2 番目の select に追加された wire:key
だけです。これにより、都道府県が変更されたときに、「selectedCity」の値が適切にリセットされます。Again, the only thing non-standard here is the wire:key
that has been added to the second select. This ensures that when the state changes, the "selectedCity" value will be reset properly.
複数選択ドロップダウンMulti-select dropdowns
「multiple」select メニューを使用している場合、Livewire は期待どおりに機能します。この例では、都道府県が選択されると $states
配列プロパティに追加され、選択解除されると削除されます。If you are using a "multiple" select menu, Livewire works as expected. In this example, states will be added to the $states
array property when they are selected and removed if they are deselected:
<select wire:model="states" multiple>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
...
</select>
さらに深く掘り下げるGoing deeper
HTML フォームのコンテキストで wire:model
を使用する方法の詳細については、Livewire フォームのドキュメントページ を参照してください。For a more complete documentation on using wire:model
in the context of HTML forms, visit the Livewire forms documentation page[/docs/forms].