// search option with ajax
// url
Route::post('/serach', 'value')->name('search.product');
// controller logic
public function value(Request $request)
{
$search = $request->searchValue;
if ($search) {
$product = Product::select('id', 'title', 'slug')
->where('title', 'Like', '%' . $search . '%')
->get();
return json_encode($product);
}else{
return response('No Product', 404);
}
}
<script>
let search = $('.search')
let search1 = $('.search1 ul')
let myurl = `{{ route('search.product') }}`
search.on('keyup', function() {
let value = $(this).val()
setTimeout(() => {
$.ajax({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}",
},
url: myurl,
type: 'post',
dataType: 'json',
data: {
searchValue: value,
},
success: function(response) {
let results = response
// console.log(results)
let lists = []
results.map(result =>{
list = `<li><a href="/view/product/${result.id}">${result.title}</a></li>`;
lists.push(list)
})
search1.html(''),
search1.html(lists)
},
error: function(){
search1.html(" ")
}
})
}, 500);
})
</script>