Laravel autocomplete search
web.php
Route::get('search', 'SearchController@autocomplete');
SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class SearchController extends Controller
{
public function autocomplete(Request $request)
{
$query = $request->get('query');
$results = User::where('name', 'LIKE', '%'. $query. '%')->get();
return response()->json($results);
}
}
layout.blade.php
/*inside head tag of layout*/
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />
/*at the closing body tag of layout*/
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<script type="text/javascript">
var route = "{{ url('search') }}";
$('#search').typeahead({
source: function (query, process) {
return $.get(route, {
query: query
}, function (data) {
return process(data);
});
}
});
</script>
/*at the closing body tag of layout*/
view.blade.php
/*inside view blade template*/
<div class="container mt-5">
<div classs="form-group">
<input type="text" id="search" name="search" placeholder="Search" class="form-control" />
</div>
</div>
click for more laravel codes, read in detail about laravel Queries