Reputation: 17303
every users when they went to register our website and they are typing username
or email
, we want to check real time which username
or password
exists in our database or not. for implementing this feature i have this input
element in blade
:
<input type="text" class="form-control"
wire:model.lazy="username"
value="{{old('username')}}">
as i'm not sure this implementation is correct i don't have any method on component
.
for example:
public function username($username){
echo "Hey {$username} !";
}
i want to know how we can fire method when we type into input
element
Upvotes: 1
Views: 1645
Reputation: 26450
Just a little note, when you wrote "which username or password exists in our database", I'm a little worried - I hope you don't check that passwords are unique, and I hope you hash them properly through the Hash
facade.
The better approach is to define some $rules
for your component, and use the built-in validation feature.
Alter your view to check for the validation errorbag instead,
<input
type="text"
class="form-control"
wire:model.lazy="username"
/>
@error('username') {{ $message }} @enderror
Then make your component use validation through the rules()
method, and using validateOnly()
in your updated()
hook.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class RegisterForm extends Component
{
public $username;
public function render()
{
return view('livewire.register-form');
}
public function updated($field)
{
$this->vbalidateOnly($field);
}
/**
* The rules for this component
*/
public function rules()
{
return [
'username' => [
'required',
'min:3',
'unique:users,email',
]
];
}
}
See the official Livewire documentation on validation.
Upvotes: 0
Reputation: 10210
The lazy
directive modifier on your input
prevents a request being sent to the server when the field is updating (150ms default debounce). If you want to provide feedback as they type, remove the lazy
modifier.
In order to determine if the username/email
is in use, you'll want to hook into the lifecycle of your username
property. By this I mean the updatedUsername
function which will fire when the value of your username
property updates in the Livewire component.
You could do something like the following (works with or without the lazy
modifier on the input field):
Livewire view
<div>
<label for="username">Username</label>
<input id="username" name="username" type="text" value="{{ old('username') }}"
wire:model="username">
<p>{{ $availability }}</p>
</div>
Livewire component
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class RegisterForm extends Component
{
public $username;
public $availability;
public function render()
{
return view('livewire.register-form');
}
public function updatedUsername()
{
if (User::where('email', $this->username)->first()) {
$this->availability = 'That username is already taken';
return;
}
$this->availability = '';
}
}
Hopefully the above is self explanitory.
Upvotes: 3