article

Wednesday, July 6, 2022

Laravel 9 Auto populate Dropdown with jQuery AJAX

Laravel 9 Auto populate Dropdown with jQuery AJAX

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create tables 

php artisan make:migration create_departments_table
php artisan make:migration create_employees_table
C:\xampp\htdocs\laravel\laravelproject>php artisan make:migration create_departments_table
C:\xampp\htdocs\laravel\laravelproject>php artisan make:migration create_employees_table


Open new migrations
yourproject/database/migrations
laravelproject\database\migrations\create_departments_table.php
laravelproject\database\migrations\create_employees_table.php

//laravelproject\database\migrations\create_departments_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
}	
//laravelproject\database\migrations\create_employees_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('username');
            $table->string('name');
            $table->string('email');
            $table->integer('department');
            $table->timestamps();
        });
    }
}	
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Create tables Model

php artisan make:model Departments
php artisan make:model Employees
C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Departments
C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Employees
laravelproject\app\Models\Departments.php
//laravelproject\app\Models\Departments.php
class Departments extends Model
{
    use HasFactory;
    protected $fillable = [
        'name'
    ];
}
laravelproject\app\Models\Employees.php
//laravelproject\app\Models\Employees.php
class Employees extends Model
{
    use HasFactory;
    protected $fillable = [
        'username','name','email','department'
    ];
}
Creating Controller

php artisan make:controller DepartmentsController
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller DepartmentsController
change it with the following codes:
laravelproject\app\Http\Controllers\DepartmentsController.php
//laravelproject\app\Http\Controllers\DepartmentsController.php
<?php

namespace App\Http\Controllers;
use App\Models\Departments; //add Departments Model
use App\Models\Employees; //add Employees Model

use Illuminate\Http\Request;

class DepartmentsController extends Controller
{
    public function index(){

        // Fetch departments
        $departmentData['data'] = Departments::orderby("name","asc")
           ->select('id','name')
           ->get();

        // Load index view
        return view('index')->with("departmentData",$departmentData);
    }

    // Fetch records
    public function getEmployees($departmentid=0){

    // Fetch Employees by Departmentid
        $empData['data'] = Employees::orderby("name","asc")
        ->select('id','name')
        ->where('department',$departmentid)
        ->get();
  
        return response()->json($empData);
     
    }
}
Route
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DepartmentsController; //add DepartmentsController

//Route::get('/', function () {
//    return view('welcome');
//});
 
Route::get('/', [DepartmentsController::class, 'index']);
Route::get('getEmployees/{id}', [DepartmentsController::class, 'getEmployees']);
Create Views
laravelproject\resources\views\index.blade.php

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
//laravelproject\resources\views\index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Auto populate Dropdown with jQuery AJAX</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <p><h1>Laravel 9 Auto populate Dropdown with jQuery AJAX</h1></p>
    <div class="row">
        <div class="col-12">
            <div class="mb-3 row">
                <label class="col-sm-2 col-form-label"><b>Department</b></label>
                <div class="col-sm-10">
                    <select id='sel_depart' name='sel_depart' class="form-select">
                        <option value='0'>-- Select department --</option>
                        @foreach($departmentData['data'] as $department)
                            <option value='{{ $department->id }}'>{{ $department->name }}</option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="mb-3 row">
                <label class="col-sm-2 col-form-label"><b>Employee</b></label>
                <div class="col-sm-10">
                    <select id='sel_emp' name='sel_emp' class="form-select">
                        <option value='0'>-- Select Employee --</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
</div>    
<script type='text/javascript'>
    $(document).ready(function(){

      $('#sel_depart').change(function(){
         // Department id
         var id = $(this).val();

         // Empty the dropdown
         $('#sel_emp').find('option').not(':first').remove();

         // AJAX request 
         $.ajax({
           url: 'getEmployees/'+id,
           type: 'get',
           dataType: 'json',
           success: function(response){
                var len = 0;
                if(response['data'] != null){
                    len = response['data'].length;
                }

                if(len > 0){
                    // Read data and create <option >
                    for(var i=0; i<len; i++){
                        var id = response['data'][i].id;
                        var name = response['data'][i].name;
                        var option = "<option value='"+id+"'>"+name+"</option>"; 
                        $("#sel_emp").append(option); 
                    }
                }
           }
        });
      });
    });
</script>
</body>
</html>
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post