UserController:
public function search(Request $request)
{
$query = $request->input('user_search');
$users = User::when($query, function ($queryBuilder) use ($query) {
$keywords = explode(' ', $query);
foreach ($keywords as $keyword) {
$queryBuilder->where(function ($subquery) use ($keyword) {
$subquery->where('name', 'like', '%' . $keyword . '%')
->orWhere('surname', 'like', '%' . $keyword . '%');
});
}
})
->paginate(5);
}
index:
<tbody id="item_wrapper">
@foreach ($users as $user)
<tr>
<th scope="row">{{ $user->id }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->surname }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone_number }}</td>
<td>{{ $user->pass_type }}</td>
<td>
<a href="{{ route('users.edit', $user->id) }}">
<button class="btn btn-success btn-sm ">
<i class="fa-solid fa-pen-to-square"></i>
</button>
</a>
<button class="btn btn-danger btn-sm delete" data-id="{{ $user->id }}">
<i class="fa-solid fa-trash-can"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
plik js:
$(function() {
$('#search_input').on('input', function(event) {
event.preventDefault();
let search_input = $(this).val();
$.ajax({
method: "GET",
url: "/users/",
data: {search_input:search_input},
})
.done(function (response) {
$('#item_wrapper').empty();
$.each(response.data, function (index, user) {
const html =
'<tr>' +
'<th scope="row">'+ user.id +'</th>' +
'<td>'+ user.name +'</td>' +
'<td>'+ user.surname +'</td>' +
'<td>'+ user.email +'</td>' +
'<td>'+ user.phone_number +'</td>' +
'<td>'+ user.pass_type +'</td>' +
'<td>' +
'<a href="{{ route("users.edit", $user->id) }}">'
'<button class="btn btn-success btn-sm ">'
'<i class="fa-solid fa-pen-to-square"></i>'
'</button>'
'</a>'
'<button class="btn btn-danger btn-sm delete" data-id="{{ $user->id }}">'
'<i class="fa-solid fa-trash-can"></i>'
'</button>'
'</td>'
'</tr>'
$('#item_wrapper').append(html);
});
});
});
});
a tu formularz:
<form class="d-flex" id="searchForm" action="{{ route('users.search') }}" method="GET">
<input id="search_input" class="form-control me-2" type="search" placeholder="Search" aria-label="Search" name="search">
</form>
zalezy mi zeby nasluchiwanie bylo na input. Probowalem cos samemu zdzialac ale nie mam juz pomyslow. Co robie nie tak?