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

nklvjvc's avatar

How to deal with big data in select

Hello, i been struggling last few days to figure how to deal with really long select dropdown. I been using select2 and either i have to load thousands of tags or using ajax where I am not able to set old() helper.

What i need is simple < select > with search that wouldn't load all data from database till its searched, and to be able to see its old value, as its necessary in edit page. Any tips how to deal with this or to point me to certain tutorials. So far this is my code, where i followed some tutorial guidance

public function getTeams(Request $request)
    {
        $search = $request->search;

        if ($search != '') {
            $teams = Team::orderBy('id', 'ASC')
            ->select('id', 'name')
            ->where(DB::raw('name', 'like', '%' .$search . '%')
            ->limit(5)
            ->get();
        }

        $response = array();

        foreach ($teams as $team) {
            $response[] = array(
                'id' => $team->id,
                'text' => $team->name
            );
        };

        return response()->json($response);
    }
<select id="team_id" name="team_id">
      <option value='0'>Select Team</option>
   </select>

   <script type="text/javascript">
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
   $(document).ready(function(){

     $( "#team_id" ).select2({
        placeholder: 'Select Team',
        minimumInputLength: 3,
        ajax: { 
          url: "{{route('admin.getteams')}}",
          type: "post",
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return {
               _token: CSRF_TOKEN,
               search: params.term // search term
            };
          },
          processResults: function (response) {
            return {
              results: response
            };
          },
          cache: true
        }

     });

   });
   </script>
0 likes
1 reply

Please or to participate in this conversation.