Why pluck() Returns an Object Instead of an Array and How to Fix It
When you use Laravel's pluck method on a query builder instance, it returns an associative array where keys come from the first column specified and values come from the second. In your specific case, $data = Districts::...->pluck('region','district') is generating a structure like:
{
"Kreis 1 \/ Altstadt": "City",
"Kreis 2": "Enge",
...
}
This happens because pluck maps every row in the database to a key-value pair based on your column selection. The result is an array of objects (which serializes as a JSON object) where the keys are the district names. However, your frontend requirement is a simple flat list of values:
["Rathaus", "Hochschulen", "Lindenhof", ...]
The mismatch occurs because pluck inherently creates a mapping structure. To get a plain array of values without keys, you need to extract only the second column and discard the first one entirely.
Extracting Values Without Keys
You can achieve this by chaining the values() method onto your query after calling pluck. The values() method transforms an associative array into a numerically indexed array containing only the values.
Here is the corrected implementation for your controller:
public function autocomplete_districts(Request $request)
{
$district = $request->input('query');
// Perform the query with two columns, then extract just the values
$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])
->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])
->pluck('region', 'district')
->values() // Converts associative array to a simple indexed array
->toArray();
return response()->json($data);
}
By adding ->values() and explicitly converting to an array with ->toArray(), you ensure that the JSON response is a clean list of strings rather than an object with string keys. This approach preserves the filtering logic while adjusting the output format exactly as your frontend expects.
Handling Empty Results
It is important to consider what happens when no records match the search query. If $district is empty or returns zero rows, pluck will return an empty array. The subsequent ->values() and ->toArray() calls will safely maintain that state, resulting in a JSON response of []. This is generally safe for AJAX autocomplete inputs, as most JavaScript libraries handle empty arrays gracefully by not rendering any suggestions.
However, if you are concerned about potential issues with how the frontend interprets an empty object versus an empty array, explicitly converting to an array ensures consistency regardless of the database state.
Performance Considerations
While this solution is clean and readable, keep in mind that using whereRaw with LOWER() functions can impact query performance on large datasets. The database must scan the entire column because it cannot use standard indexes when applying case-insensitive transformations or wildcard matching (%...%) directly in SQL unless those wildcards are handled carefully.
If your dataset grows significantly, consider creating a functional index on a lowercase version of the district column to speed up these lookups. Alternatively, normalize the data by storing both the original and lowercased values in separate columns if case-insensitive search is a frequent requirement. This allows you to use standard indexed queries without relying on LOWER() inside the WHERE clause.
Final Thoughts on Data Structure
The core issue was not with the query logic itself, but with the expectation of the output format. Laravel's Eloquent makes it easy to reshape data structures using methods like pluck, only, and values. Understanding what each method returns is crucial when building APIs that serve specific JSON schemas. If you ever find yourself needing a subset of an associative array as a simple list, remember that ->values() is the standard tool for stripping keys and retaining only the payload values.
