Dynamic drop down with laravel and jquery

“Displaying dynamic options in the drop down based on value selected in another drop down” is one of the most commonly used functionality in form handling. Sometime, we want to display a list of products based on category, a list of subjects based on faculty, a list of cities based on country and many more. This might look quite difficult but we can achieve easily with few lines of java script and laravel code.

We will take and example of category and products. This is quite easy to understand. Here, one category can have multiple products and one product is associated with only one category.

Part I ( Back End)

Let’s start with database schema for category and product,

We will use artisan commands to create schema. Just run following artisan command,

Now, make category schema like following.

Again run following artisan command,

Now, make product schema like following.

Now, we will create model for each of these database table and then we will define one to

many relationship,

Artisan Command:

Category Model:

Artisan Command:

Product Model:

Here, one category can have multiple products and one product is associated with only one category.

We have to display all products by default. After selecting certain category, we need to display products associated with the category only.

We can add data to the database directly but proper way is the use of seeder for this thing. Now, Lets add some categories and products to the database using seeder.

We will use following artisan command to create database seeder,

Now, add some products and categories.

Lets register this seeder to Database Seeder,

Now, run following artisan commands.

Lets add some code to our controller,

In order to return all products and categories, we will use index method and to return products of a category we will use the second function.

In order to register these controller functions to the route, we need to add following lines of code to our route file web.php

Part II ( Front End )

Now, we will see what our html code should be,


Now, we will use Ajax call to add products dynamically based on category.


Here, we can send a get request and then on successful call json array of products data will be received.

And here we finished. Now, You can just use it and enjoy.



Computer Enginner, A Laravel Developer,

Leave a Reply

Your email address will not be published. Required fields are marked *