Laravel 10: Autocomplete search from multiple fields & tables

Hello Team,
I’m working on a project that requires searching the first name and last name fields from the user table as well as search a group field from a groups table. I found a tutorial online but I couldn’t finesse the script to get it working. It works if your searching the one field from the user table but I need to expand the search.

Any assistance you can provide would be greatly appreciated.

Laravel 10 controller function

public function autocomplete(Request $request): JsonResponse
    {
        $data = User::select("name")
                    ->where('name', 'LIKE', '%'. $request->get('query'). '%')
                    ->get();         
        return response()->json($data);
    }

script

<script type="text/javascript">
    var path = "{{ route('autocomplete') }}";
  
    $('#search').typeahead({
            source: function (query, process) {
                return $.get(path, {
                    query: query
                }, function (data) {
                    return process(data);
                });
            }
        });
  
</script>

You will need to use a UNION query - https://laravel.com/docs/10.x/queries#unions to produce a result set that contains rows from the two different tables.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.