Requirement
In blade file
<div class="input_box">
<input id="search_query" name="search_query" type="text" class="form-control fs-4 fw-semi py-4 @error('search_query') is-invalid @enderror" value="{{ old('search_query') ? old('search_query') : (isset($last_search_query) ? $last_search_query : '') }}" placeholder="Location" autocomplete="off">
<div class="search-results" style="display:none">
<ul class="list-group text-left" ></ul>
</div>
In javascript
$('#search_query').on('input', function() {
var query = $(this).val();
var MIN_QUERY_LENGTH = 1;
if (query.length >= MIN_QUERY_LENGTH) {
$.ajax({
url: "{{ route('autocomplete.search_query') }}",
method: "POST",
data: { query: query, _token: "{{ csrf_token() }}" },
success: function(data) {
$('.search-results ul').empty();
selected = -1;
if (data.length > 0) {
$.each(data, function(key, value) {
$('.search-results ul').append('<li class="list-group-item">'+value+'</li>');
});
$('.search-results').show();
} else {
$('.search-results').hide();
}
}
});
} else {
$('.search-results').hide();
}
});
In controller
public function getStateAndCity(Request $request){
$search_query = empty($request->input('query')) ? null : $request->input('query');
/* Working Query *////
$query = DB::table('items')->leftJoin('states', 'items.state_id', '=', 'states.id')->leftJoin('cities', 'items.city_id', '=', 'cities.id');
if ($search_query) {
$query->where(function($q) use ($search_query) {
$q->where('cities.city_name', 'like', "$search_query%")->orWhere('cities.city_state', 'like', "$search_query%");
});
}
$data = $query->get();
$result = array();
if(!empty($data)){
foreach($data as $key=>$val):
$result[] = $val->city_name. ', ' . $val->state_abbr;
endforeach;
}
return response()->json($result);
}
In above sql query output of one query connected to another query
First query
$query = DB::table('items')->leftJoin('states', 'items.state_id', '=', 'states.id')->
leftJoin('cities', 'items.city_id', '=', 'cities.id');
Second Query
if ($search_query) {
$query->where(function($q) use ($search_query) {
$q->where('cities.city_name', 'like', "$search_query%")->orWhere('cities.city_state', 'like', "$search_query%");
});
}
$data = $query->get();
Top comments (0)