Requirement
Solution
foreach($data as $key=>$val):
         $result[] = $val->city_name. ', ' . $val->city_state;
        endforeach;
         }
In Controller
     public function getStateAndCity(Request $request){
        $search_query = empty($request->input('query')) ? null : $request->input('query');
        /* Working Query *////
        $query = DB::table('cities')->leftJoin('states', 'cities.state_id', '=', 'states.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 blade file
 var path = "{{ route('autocomplete.search_query') }}";
   $('#search_query').typeahead({
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
                return process(data);
            });
        }
    });
Another Solution
Assuming that you have an array of data in your Laravel controller that contains cities and states, and you want to print this data using a foreach loop, here's an example code snippet that demonstrates how to achieve this:
$data = [
    ['city' => 'New York', 'state' => 'NY'],
    ['city' => 'Los Angeles', 'state' => 'CA'],
    ['city' => 'Chicago', 'state' => 'IL'],
    // more data here...
];
foreach ($data as $item) {
    echo $item['city'] . ', ' . $item['state'] . '<br>';
}
In this example, $data is an array of associative arrays, where each associative array contains the city and state values. The foreach loop iterates over each item in the $data array, and for each item, it prints the city and state values separated by a comma and a space, followed by an HTML 
 tag to create a line break.
You can modify this code to match your specific data structure and formatting requirements. For example, you may want to wrap the printed values in HTML tags or use a different delimiter between the city and state values.
Top comments (0)