I am working on a search autocomplete box in Laravel
Form Code in View
<form action = "/searchresult" method = "post">
{{ csrf_field() }}
<input type="text" class="form-control" placeholder="Search Stores, Coupons or Deals" name="mysearch" id="mysearch">
<div class="input-group-btn">
<button class="btn btn-search" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</form>
Route
Route::get('/search/autocomplete', ['uses' =>'SearchController@autocomplete']);
JS
$( "#mysearch" ).autocomplete({
source: "search/autocomplete",
minLength: 1,
autoFocus: true,
select: function(event, ui) {
window.location.href = "/deals-coupons/" + ui.item.url;
},
focus: function( event, ui ) { event.preventDefault();}
});
Controller Method
public function autocomplete(Request $request)
{
$term = $request->input('mysearch');
// $term = $request->get('mysearch');
Log::info('Search Term: '.$term);
$results = array();
$queries = DB::table('merchants')
->where ('merchant_name','LIKE', $term.'%')
->take(5)
->get();
foreach ($queries as $query)
{
// Log::info('Query: '.$query);
$results[] = ['id' => $query->merchant_id, 'value' => $query->merchant_name, 'url' => $query->merchant_url_text];
}
return $results;
}
I have tried the following
$term = $request->get('mysearch');
$term = $request->input('mysearch');
but none of these is returning the search term I am trying to type. As you can see I am logging the search term in my laravel.log file and each time it is coming empty. Because the term is empty it is always showing top 5 results from the merchants table.
Can someone please help me understand what mistake I am doing.
You can try following
$('#mysearch').autocomplete ({
minLength : 1,
autoFocus : true,
source : '/search/autocomplete'
});
$term = $_GET['mysearch'];
I was able to get this working.
On the server side, it was about using
$term = $request->input('term'); instead of $term = $request->input('mysearch');