I have developed a search bar to search items from my products list where more than 10,000 products available. When a user type a word user can see suggestion list with 8 items based on user input. This is my code and code is working perfectly. But what I wants to do is to increase the suggestion list. I have no idea how to that. So if anyone could please help me.
Nsearch.blade.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script>
</head>
<body>
<div class="container">
<h1> test products </h1>
<input type="text" class="typeahead form-control" name="name">
</div>
<script type="text/javascript">
var path = "{{route('nautocomplete')}}";
$('input.typeahead').typeahead({
source:function(query,process){
return $.get(path,{query:name},function (data) {
return process(data);
})
}
});
</script>
</body>
</html>
NSearchController.php
<?php
namespace App\Http\Controllers\Shop;
use App\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class NSearchController extends Controller
{
public function index(){
return view('shop.Nsearch');
}
public function autocomplete(Request $request){
$data = Product::select("name")
->where("name","LIKE","%{$request->input('name')}%")->get();
return response ()->json($data);
}
}
web.php (route)
Route::get ('/nsearch','Shop\NSearchController@index')->name('nsearch');
Route::get ('/nautocomplete', 'Shop\NSearchController@autocomplete')->name('nautocomplete');
Current view
I think it's your front-end issue.
$('input.typeahead').typeahead({
items: 20,
source: function(query,process){
return $.get(path,{name:query},function (data) {
return process(data);
})
}
});
Read Bootstrap 3 Typeahead documentation in this link
Have you ever dumped $data
in your NSearchController.php
and see the result count?
Another thing that you should care:
in you controller you are using $request->input('name')
, it means you should receive 'name' as a query string; while you are using $.get(path,{query:name}
and it's wrong. You should change it to $.get(path,{name:query}
. in your code $request->input('name')
always return null and SQL query will return all of your products name; then typehead will filter them on your frontend –
just set another value to items
property. (It's 8 by default)