How to create dependent dropdown list by using jquery, ajax, and laravel

Published Date: 25-Nov-2017 | Tags: Laravel 5.5  JQuery  Ajax  

This tutorial I want to show you how to filter data within a dropdown list base on a selected value of another dropdown list by using jquery ajax and laravel 5.5.

Suppose that your server is running on port 80 and your project folder is /demo.

Note

  • I use laravelcollective to create form. So please install laravelcollective if you not yet install it. You can visit here for the installation guide.
  • I use bootstrap 4 for my UI, so please check bootstrap if you are new to bootstrap.

 

Step 1: Create Database Table

 Create table products and product_categories with structure as below and enter some data.

products
product table structure

product_categoriesproduct_category table structure
or you download sample data from here and restore to your database.

 

Step 2: Database Configuration

Edit this file /demo/.env and update your database name, username and password.

Suppose that your database name is demo, username is root, and password is empty.

laravel db config

 

Step 3: Add Route

Add these lines to this file /demo/routes/web.php.

Route::get('/dependent-dropdown-list', 'DropdownListController@dependentDropdownList');
Route::get('/get-products/{product_category_id}', 'DropdownListController@getProducts');

 

Step 4: Create Model

Create 2 model files Product.php and ProductCategory.php in /demo/app.

Product.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

}

ProductCategory

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductCategory extends Model
{

}

 

Step 5: Create View

Create layout view file default.blade.php in /demo/resources/views/layout. (create folder layout if it does not exist)

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
@yield('head')
<!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    @yield('css')
</head>
<body style="padding-top: 100px;padding-bottom: 50px;background: whitesmoke">
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-info">
    <a class="navbar-brand" target="_blank" href="http://codingstep.com">CODINGSTEP.COM</a>
    @yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
@yield('js')
</body>
</html>

 

Create view file dependent_dropdown_list.blade.php in /demo/resources/views.

@extends('layout.default')
@section('content')
    <div class="container">
        <div class="col-md-8 offset-md-2">
            <h1 style="font-size: 1.5rem;">JQuery dependent dropdown list with laravel</h1>
            <hr/>
            <div class="form-group row">
                {!! Form::label("product_category","Product Category",["class"=>"col-form-label col-md-3"]) !!}
                <div class="col-md-6">
                    {!! Form::select("product_category",\App\ProductCategory::pluck('name','id'),null,["class"=>"form-control"]) !!}
                </div>
            </div>
            <div class="form-group row">
                {!! Form::label("product","Product",["class"=>"col-form-label col-md-3"]) !!}
                <div class="col-md-6">
                    {!! Form::select("product",[],null,["class"=>"form-control"]) !!}
                </div>
            </div>
        </div>
    </div>
@endsection
@section('js')
    <script>
        $('#product_category').on('change', function () {
            getProducts($(this).val());
        });
        function getProducts(product_category_id) {
            $.get("{{url('/get-products')}}/" + product_category_id, function (data) {
                $("#product").html(data);
            });
        }
        $(document).ready(function () {
            getProducts($('#product_category').val());
        });
    </script>
@endsection

 

Step 6: Create Controller

Create controller file DropdownListController in /demo/app/Http/Cotrollers.

<?php

namespace App\Http\Controllers;

use App\Product;

class DropdownListController extends Controller
{
    public function dependentDropdownList()
    {
        return view('dependent_dropdown_list');
    }

    public function getProducts($product_category_id)
    {
        $products = Product::where('product_category_id', $product_category_id)->pluck('name', 'id');
        $list = '';
        foreach ($products as $key => $value) {
            $list .= "<option value='" . $key . "'>" . $value . "</option>";
        }
        return $list;
    }
}

 

Step 7: Test

Open your browser and type http://localhost/demo/public/dependent-dropdown-list. Then you will see it.

dependent dropdown list screenshot

Hope you can do it.


Demo


© 2018 All Rights Reserved.