Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

michaelabraham's avatar

Laravel How to make multiple autocomplete form from two diferent tables?

So i was trying to make a form with multiple fields, and each field has an autocomplete that was fetched from a table in database, but each field has a different autocomplete suggestion beacause it's from different tables.

i was following a tutorial that only show me how to make a single autocomplete field from a single table. but i am stuck when i try to make a second field, well it does show the data from the different table, but when i clicked it it chose the same suggestion to the other field automaticaly, and when i try to change the others when i clicked it the other are filling the same value automaticaly

this is my AutocompleteController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class AutocompleteController extends Controller
{
    //for create controller - php artisan make:controller AutocompleteController

    function index()
    {
     return view('autocomplete');
    }

    function fetchcpu(Request $request)
    {
     if($request->get('query'))
     {
      $query = $request->get('query');
      $data = DB::table('cpu')
        ->where('name', 'LIKE', "%{$query}%")
        ->get();
      $output = '<ul class="dropdown-menu" style="display:block; position:relative">';
      foreach($data as $row)
      {
       $output .= '
       <li><a href="#">'.$row->name.'</a></li>
       ';
      }
      $output .= '</ul>';
      echo $output;
     }
    }

    function fetchvga(Request $request)
    {
     if($request->get('query'))
     {
      $query = $request->get('query');
      $data = DB::table('vga')
        ->where('namevga', 'LIKE', "%{$query}%")
        ->get();
      $output = '<ul class="dropdown-menu" style="display:block; position:relative">';
      foreach($data as $row)
      {
       $output .= '
       <li><a href="#">'.$row->namevga.'</a></li>
       ';
      }
      $output .= '</ul>';
      echo $output;
     }
    }

}

this is my view

@extends('layouts.master')
@section('content')
    <!-- Page top section -->
    <section class="page-top-section set-bg" data-setbg="../public/asset/img/page-top-bg/2.jpg">
        <div class="page-info">
            <h2>Spesifikasi Sistem</h2>
            <div class="site-breadcrumb">
                <a href="">Tentang</a>  /
                <span>Spesifikasi Sistem</span>
            </div>
        </div>
    </section>
    <!-- Page top end-->
<!DOCTYPE html>
<html>
 <head>
  <title>Ajax Autocomplete Textbox in Laravel using JQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <section class="contact-page">
        <div class="container">  
            <div class="form-group">
                <label style="color: white">CPU :</label>
                <input type="text" name="name" id="name" class="form-control input-lg" placeholder="Masukan Tipe CPU" />
                    <div id="cpuList"></div>
                <label style="color: white">VGA :</label>
              <input type="text" name="namevga" id="namevga" class="form-control input-lg" placeholder="Masukan Tipe CPU" />
                <div id="vgaList"></div>
            </div>
            {{ csrf_field() }}
        </div>
    </section>


<script>
$(document).ready(function(){

 $('#name').keyup(function(){ 
        var query = $(this).val();
        if(query != '')
        {
         var _token = $('input[name="_token"]').val();
         $.ajax({
          url:"{{ route('autocomplete.fetchcpu') }}",
          method:"POST",
          data:{query:query, _token:_token},
          success:function(data){
           $('#cpuList').fadeIn();  
                    $('#cpuList').html(data);
          }
         });
        }
    });

$('#namevga').keyup(function(){ 
        var query = $(this).val();
        if(query != '')
        {
         var _token = $('input[name="_token"]').val();
         $.ajax({
          url:"{{ route('autocomplete.fetchvga') }}",
          method:"POST",
          data:{query:query, _token:_token},
          success:function(data){
           $('#vgaList').fadeIn();  
                    $('#vgaList').html(data);
          }
         });
        }
    });


    $(document).on('click', 'li', function(){  
        $('#name').val($(this).text());  
        $('#cpuList').fadeOut();  
        $('#namevga').val($(this).text());  
        $('#vgaList').fadeOut();  

    });  

});
</script>

@endsection

and this is my routes

Route::get('/autocomplete','AutocompleteController@index');
Route::post('/autocomplete/fetchcpu','AutocompleteController@fetchcpu')->name('autocomplete.fetchcpu');
Route::post('/autocomplete/fetchvga','AutocompleteController@fetchvga')->name('autocomplete.fetchvga');
0 likes
3 replies
bobbybouwmann's avatar

I don't see anything strange. So if you do only one field (only the first or only the second) it does work for you?

mstrauss's avatar
mstrauss
Best Answer
Level 14

It might be this:

    $(document).on('click', 'li', function(){  
        $('#name').val($(this).text());  
        $('#cpuList').fadeOut();  
        $('#namevga').val($(this).text());  
        $('#vgaList').fadeOut();  

    });  

So when the user clicks on the li (assuming this is the value the user selects from the autosuggest list), the value they selected which is $(this).text() is set as the value for both the #namevga and the #name fields.

So maybe you have to uniquely identify what the user selected and then react:

$(document).on('click', '#cpuList li', function(){  
        $('#name').val($(this).text());  
        $('#cpuList').fadeOut();  
    });  


$(document).on('click', '#vgaList li', function(){  
        $('#namevga').val($(this).text());  
        $('#vgaList').fadeOut();   
    });  
1 like
michaelabraham's avatar

ouw so that's how ot works, thanks a lot @mstrauss, now i know how to make the other fields and tables

1 like

Please or to participate in this conversation.