Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

laravel - Livewire fire method when we type into input element

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 AppHttpLivewire;

use AppModelsUser;
use LivewireComponent;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...