I have a form in the Laravel Livewire project and try to search and select users from the database. When I search User then search results in users, but nothing to select. Also, no error showing just page refresh. my code is below: I'm trying this

livewire component view
<div> <div> <label>Select User</label> <div> <div> <select wire:model="user_id" name="user_id" required> <option></option> @foreach($users as $user) <option value="{{$user->id}}">{{$user->username}} : {{ $user->fullname }}</option> @endforeach </select> </div> <div> <input wire:model.debounce.500ms="inputsearchuser" type="text" placeholder="search..."/> </div> <div> @if(strlen($inputsearchuser)>2) @if(count($searchusers)>0) <ul> @foreach($searchusers as $searchuser) <li> <spanwire:click ="selectuser({{$searchuser->id}},{{$searchuser->terms}})">{{$searchuser->username}} : {{$searchuser->fullname}}</span> </li> </ul> @endforeach @else <li>User Not Found...</li> @endif @endif </div> </div> </div> </div> 
livewire component
class MyLiveWireComponent extends Component { public $j = 1; public $users = []; public $inputsearchuser = ''; public $user_id; public function selectuser($user_id,$terms) { $this->user_id = $user_id; $this->terms = $terms; $this->inputsearchuser = ''; } public function render() { $searchusers = []; if (strlen($this->inputsearchuser) >= 2) { $searchusers = User::Where('username', 'LIKE', '%' . $this->inputsearchuser . '%') ->get(); } return view('livewire.admin.orders.add-order', ['searchusers' => $searchusers])->layout('components.layouts.admin'); } } 
4

3 Answers

Change this:

<spanwire:click="selectuser({{$searchuser->id}},{{$searchuser->terms}})"> {{$searchuser->username}} : {{$searchuser->fullname}} </span> 

To:

<span wire:click.prevent="selectuser({{$searchuser->id}},{{$searchuser->terms}})"> {{$searchuser->username}} : {{$searchuser->fullname}} </span> 
1

Your component should have a single-level root element only. Also, add wire:key in your element inside of the loop.

 <ul> @foreach($searchusers as $key => $searchuser) <li wire:key="{{'users'.$key}}"> <span wire:click="selectuser({{$searchuser->id}}, {{$searchuser->terms}})">{{$searchuser->username}} : {{$searchuser->fullname}}</span> </li> @endforeach </ul> 

Did you change it to wire:click.prevent as suggested above? Otherwise, it does not prevent the default action from occurring, and can cause that exact behavior.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.