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

christopher's avatar

City Search

Hey,

currently i`m thinking about how to make a city search.

We have ober 2000 citys, so i think it`s not a good idea if the search form loads all cities everytime ?

Is there any jQuery Tutorial or something like this ?

I think the best would be if a user type some letters an laravel gives some suggestions and then filter through the cities ?

0 likes
9 replies
bashy's avatar

You can do an ajax/jquery request to a URI that pulls in matches when someone types something into an input. Can also limit the amount to a minimum of two characters etc so it wouldn't pull all the entries in.

If they're static or not changing a lot, maybe cache them as well?

ekaitzastiz's avatar

An example with select2. I think it's a powerful library!!! download select2.js and just add the styles and js files.

@section('styles')

{{ HTML::style('css/select2.css')}}
{{ HTML::style('css/select2-bootstrap.css')}}

@stop
.....

                                                <div class="col-md-7">
                                                    {{Form::text('city_id',0,['class'=>'form-control input-sm','required'=>'','id'=>'city_id'])}}
                                                    <span class="help-block text-center">cities</span>
                                                </div>

.....
@section('scripts')
    {{ HTML::script('js/select2.min.js')}}
    {{ HTML::script('app-js/citySearch.js'); }} 
    <script type="text/javascript">
    //init with the values you saved (if it's the case that you are asking for)
        citySeach(true);


        $("#city_id").select2('data', [
            @foreach ($cities as $city)
                   {id:{{ $city->id }},text:"{{ $city->name.' '.$city->postCode }}"},
             @endforeach
          ]);
    </script>    

@stop

Maybe, and if its the case, when you save, and if it's multiple you can do in the controller $cities = Input::get('city_id',''); $city_id_array = explode(',',$cities); ->sync($city_id_array') or if it just one value fiels city_id or for other thing just directly use $city

citySearch.js

function citySeach(multi)
{
$('#city_id').select2({
    placeholder: "search city",
    minimumInputLength: 3,
    allowClear: true,
    multiple: multi,
    ajax: {
        url: BASE+'/city/search',
        dataType: 'json',
        quietMillis: 100,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            var myResults = [];
            $.each(data, function (index, item) {
                myResults.push({
                    id: item.id,
                    text: item.name+' '+item.postCode
                });
            });
            return {
                results: myResults
            };
        }
    }
});
}

this is only a snippet, idea, of a case where I use select2 ...

if you need to return to that input you should do something like this!

christopher's avatar

Your example seems not to work. Currently i have this:

        $(document).ready(function() {

                 var data=[ @foreach($city as $city){id:{{ $city->id }},tag:'{{ $city->city }}'},@endforeach];
                 function format(item) { return item.tag; }

                 $("#e10_2").select2({
                     data:{ results: data, text: 'tag' },
                     formatSelection: format,
                     formatResult: format,
                     placeholder: 'Suche nach Stadt',
                 });

         });

But this loads all 5000 results, how can i fetch for example the first 20 results and if a user search for something select2 searches "live" via ajax in the database and return the result ?

christopher's avatar
christopher
OP
Best Answer
Level 30

Okay now it`s working. For all others:

My Method:

public function getCity()
    {
        $name = Input::get('e10_2');
        return Company::select(array('id', DB::raw('concat(city) as text')))->where(DB::raw('concat(city)'),'like', "%$name%")->get();
    }

My Route

Route::get('getcity', 'CompanyController@getCity');

My JS

  $('#e10_2').select2({
                     placeholder: 'Searching for city',
                     minimumInputLength: 3,
                     ajax: {
                         url: '/getcity',
                         dataType: 'json',
                         data: function (term, page) {
                             return {
                                 e10_2: term
                             };
                         },
                         results: function (data, page) {
                             return {results: data};
                         }
                     },
                     tags: true
                 });
ekaitzastiz's avatar

Ok. Mine does not work because i just copy snippets and I changed things here in code, because I speak-write some things in Basque, and I put them in English, so probably someting broke or I forgot something! But I just wanted to give you some idea or new way to do it.

christopher's avatar

If you paste your code maybe we can help you ;) And it`s always a good idea to write code in english and not in your own language, just because of that ;)

ekaitzastiz's avatar

No, I am saying that my code work fine, but the code I pasted here does not. Juts I wanted to send the idea. Thank you @bashy and @hostianer

Please or to participate in this conversation.