Skip to content

Instantly share code, notes, and snippets.

@msurguy msurguy/DB.sql
Last active Jun 26, 2019

Embed
What would you like to do?
Dynamic dropdown in Laravel, let's say you have multiple drop downs (selects), you click on one and the contents of the other need to be dynamically changed. One solution is to dynamically load JSON from the API and change the dropdown dynamically depending on the user choice.
CREATE TABLE `makers` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `makers`
--
INSERT INTO `makers` (`id`, `name`, `description`, `created_at`, `updated_at`) VALUES
(1, 'Toyota', 'Toyota cars', '2013-03-11 00:00:00', '2013-03-11 00:00:00'),
(2, 'Honda', 'Honda cars', '2013-03-11 00:00:00', '2013-03-11 00:00:00'),
(3, 'Mercedes', 'Mercedes cars', '2013-03-11 00:00:00', '2013-03-11 00:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `models`
--
CREATE TABLE `models` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`maker_id` int(10) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `models` (`id`, `maker_id`, `name`, `description`, `created_at`, `updated_at`) VALUES
(1, 2, 'Honda S2000', '', '2013-03-11 22:32:07', '2013-03-11 22:32:07'),
(2, 2, 'Civic', '', '2013-03-11 22:32:46', '2013-03-11 22:32:46'),
(3, 2, 'Fit', '', '2013-03-11 22:34:35', '2013-03-11 22:34:35'),
(4, 1, 'asdf asdf', '', '2013-03-11 22:35:31', '2013-03-11 22:35:31'),
(5, 1, 'Yaris', '', '2013-03-11 22:36:01', '2013-03-11 22:36:01'),
(6, 1, 'Corolla', '', '2013-03-11 22:36:23', '2013-03-11 22:36:23'),
(7, 1, 'Camry', '', '2013-03-11 22:36:31', '2013-03-11 22:36:31'),
(8, 3, 'SLK 500', '', '2013-03-11 22:36:47', '2013-03-11 22:36:47'),
(9, 3, 'C300', '', '2013-03-11 22:36:50', '2013-03-11 22:36:50'),
(10, 2, 'another item', '', '2013-03-11 22:36:52', '2013-03-11 22:36:52');
<?php
class Maker extends Eloquent {
public function models(){
return $this->has_many('Model');
}
}
?>
<?php
class Model extends Eloquent {
public function maker(){
return $this->belongs_to('Maker');
}
}
?>
Route::get('api/dropdown', function(){
$input = Input::get('option');
$maker = Maker::find($input);
$models = $maker->models();
return Response::eloquent($models->get(['id','name']));
});
jQuery(document).ready(function($){
$('#make').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var model = $('#model');
model.empty();
$.each(data, function(index, element) {
model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
});
});
});
});
<h1>Dropdown demo</h1>
{{ Form::open() }}
<select id="make" name="make">
<option>Select Car Make</option>
<option value="1">Toyota</option>
<option value="2">Honda</option>
<option value="3">Mercedes</option>
</select>
<br>
<select id="model" name="model">
<option>Please choose car make first</option>
</select>
{{ Form::close();}}
@INDIAN2020

This comment has been minimized.

Copy link

commented Jan 30, 2014

Please clarify how to dynamically load JSON from the API in this dropdown list point in Laravel4

@heidilux

This comment has been minimized.

Copy link

commented May 2, 2014

Worked after changing

Response::eloquent

to

Response::make

Not sure if that was just an issue with my setup, but that worked for me

@ghost

This comment has been minimized.

Copy link

commented Jun 1, 2014

I had to make these changes to make it work (I'm using Laravel 4).
Changed the route to:

Route::get('api/dropdown', function(){
    $id = Input::get('option');
    $models = Maker::find($id)->models;
    return $models->lists('name', 'id');
});

And the script:

$(document).ready(function($){
    $('#make').change(function(){
        $.get("{{ url('api/dropdown')}}", 
        { option: $(this).val() }, 
        function(data) {
            $('#model').empty(); 
            $.each(data, function(key, element) {
                $('#model').append("<option value='" + key +"'>" + element + "</option>");
            });
        });
    });
});
@dhritimanh

This comment has been minimized.

Copy link

commented Jun 30, 2014

Oh that's awesome Sir . It rocked ! Laravel is nothing without its freaking awesome community ! !!

Js script

$(document).ready(function($){
$("#country_id").change(function(){
$.get("{{ url('/api/dropdown')}}",
{ option: $(this).val() },
function(data) {
$('#state').empty();
$.each(data, function(key, element) {
$('#state').append("" + element + "");
});
});
});
});
}

And this is the route :

{Route::get('/api/dropdown', function(){
$id = Input::get('option');
$id_num = DB::table('countries')->where('iso',$id)->pluck('id');
$states = DB::table('states')->where('country_id',$id_num)->lists('name', 'id');
return $states;
});

@azmek

This comment has been minimized.

Copy link

commented Aug 8, 2014

Hi Msurguy,
I am noob to laravel and i was following the above code but can't figure out what do you mean by api/dropdown, where does it come from? what's in the dropdown, or what shall i put in there?
Any assistance would be much appreciated

@chokbunthit

This comment has been minimized.

Copy link

commented Aug 14, 2014

thank you, i customize functions reload datatables good.

var oTable;     
function myFunction(dept) {
    // Example call to load a new department
    oTable.fnReloadAjax( "{{ url('/asset/department')}}"+"?option="+dept );      
    // Example call to reload from original file
    //oTable.fnReloadAjax();
}   
jQuery(document).ready(function($){
    oTable = $('#example').dataTable({"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
            var status = aData[6];
            switch (status) {
                case 0:
                    $('td:eq(6)', nRow).html( '<span class="label label-success">ยกเลิก</span>' );                       
                    break;
                case 1:
                    $('td:eq(6)', nRow).html( '<span class="label label-success">ปกติ</span>' );                        
                    break;
                case 2:
                    $('td:eq(6)', nRow).html( '<span class="label label-success">หยุดซ่อมบำรุง</span>' );
                    break;
                case 3:
                    $('td:eq(6)', nRow).html( '<span class="label label-success">ซ่อมบำรุงเฉิงป้องกัน</span>' );                        
                    break;
            }       
        }});
    var dept;
    $('#make').change(function(){
        dept =  $(this).val();
        myFunction(dept);
        /*$.get("{{ url('/asset/department')}}",
                { option: dept },
                function(data) {
                var model = $('#model');
                model.empty();
                $.each(data, function(index, element) {
                model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
                });
        });*/
    });     
});
@jasonherndon

This comment has been minimized.

Copy link

commented Oct 20, 2014

I modified this a little bit and got it to work well:

routes.php

Route::get('/myurl/', ['as' => 'items.duplicate', 'uses' => 'ItemsController@duplicate']);

ItemsController.php

    public function duplicate()
    {
        $user = Input::get('option');
        $items = Items::where('user_id', '=', $user)->lists('name', 'id');
        return Response::make($items);
    }

show.blade.php

<select id="userselect" name="userselect">
    <option>Select User</option>
    @foreach ($users as $user)
      <option value="{{ $user->id }}">{{ $user->name}}</option>
    @endforeach
   </select>

   <select id="itemselect" name="itemselect">
       <option>Please choose user first</option>
   </select>


<script>
    jQuery(document).ready(function($){
        $('#itemselect').change(function(){
                $.get("{{ url('myurl')}}", 
                { option: $(this).val() }, 
                function(data) {

                    var item = $('#itemselect');
                    item.empty();

                    $.each(data, function(key, value) {
                        item.append("<option value='"+ key +"'>" + value + "</option>");
                    });

                });
        });


    });

</script>
@goranata

This comment has been minimized.

Copy link

commented Oct 25, 2014

I've done everything as suggested, and I get this error: Call to a member function models() on a non-object.

Anybody might have an idea, what the that I'm facing is about ?

@gbelot2003

This comment has been minimized.

Copy link

commented Nov 10, 2014

I don't understand how Laravel would't have a Form::selectdb(field.id) where field.id is the key relationship, to generate the drop down select box without relay on jq??? I mean "Kumbiaphp" is a more more less developed framework, but already has it since years!!!!

@sparkandy

This comment has been minimized.

Copy link

commented Nov 10, 2014

I keep having this error.. Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException

when I look at the console I see this $others = $this->checkForAlternateVerbs($request);

    if (count($others) > 0)
    {
        return $this->getOtherMethodsRoute($request, $others);
    }

    throw new NotFoundHttpException;
}

from the url.. Apprently, my route is wrong...

@josephrexme

This comment has been minimized.

Copy link

commented Mar 18, 2015

For those that keep having an issue with this, I have simplified it in step 3 of the article here http://josephrex.me/implementing-dynamic-drop-down-or-dependent-list-in-laravel4/

@yassinali

This comment has been minimized.

Copy link

commented Nov 19, 2015

Can anyone send the me the full code with the api please.

@elbiheiry

This comment has been minimized.

Copy link

commented Dec 13, 2015

i keep having this error:
ErrorException in helpers.php line 686:
Object of class stdClass could not be converted to string
how can i solve it

@ChamandeepSingh

This comment has been minimized.

Copy link

commented Dec 22, 2015

I got an error 500 Internal Server Error

i put all changes, please suggest if you have solution

@scoutkirkolson

This comment has been minimized.

Copy link

commented Jan 21, 2016

Is it possible to keep (or refill) the dropdown options and the dropdown value when the page reloads, say after a validation that didn't pass?

@gildniy

This comment has been minimized.

Copy link

commented Feb 10, 2016

For L5.2 users remember to add 'Input' => Illuminate\Support\Facades\Input::class, in your config/app.php it was removed! And run php artisan ide-helper:generate

@gildniy

This comment has been minimized.

Copy link

commented Feb 26, 2016

Here I avail a practical example of this on Laravel 5.2 fresh installation, as a package!

@mandeepkumar0856

This comment has been minimized.

Copy link

commented Aug 5, 2016

i have a question here if i have four table like as users,repo,remote,cake. and user_id is relationship with rest of all table.when i want to add a new entry in any of rest three table then user_id show in dropdown and it show the total number of user _id here.
ex. in my cake table i have 5 column like as id,title,status,user_id,created_at,updated_at
and now i want to add,edit any entry in cake table .then here user_id showin dropdown and when i click any one then it save in database table.Please tell me here for controller,view

@ruhinacse14

This comment has been minimized.

Copy link

commented Mar 2, 2017

please help editing selected value using ajax request.

@fhfg

This comment has been minimized.

Copy link

commented Apr 11, 2017

please help editing selected value using ajax request.

@sujatacodebrew

This comment has been minimized.

Copy link

commented Mar 19, 2019

<script> jQuery(document).ready(function($){ $('.country').change(function(){ $.get("{{ url('/dropdown')}}", { option: $(this).val() }, function(data) { $('city').empty(); $.each(data, function(index, element) { city.append("" + element.name + ""); }); }); }); }); </script>

Hi this code is not working, when we click on the city dropdown it doesn't display anything but the country dropdown is working fine. Can you explain Please help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.