Autopopulating values require when need to load records on child element based on parent element value.
Element values replace with new items whenever the parent element value changes.
In this tutorial, I show how you can auto-populate dropdown with jQuery AJAX in Laravel.

Contents
1. Database Configuration
Open .env file.
Specify the host, database name, username, and password.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=tutorial DB_USERNAME=root DB_PASSWORD=
2. Table structure
- Create
departmentsandemployeestable using migration and add some records.
php artisan make:migration create_departments_table php artisan make:migration create_employees_table
- Now, navigate to
database/migrations/folder from the project root. - Find a PHP file that ends with
create_departments_tableand open it. - Define the table structure in the
up()method.
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
- Similarly, find a PHP file that ends with
create_employees_tableand open it. - Define the table structure in the
up()method.
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();
});
}
- Run the migration –
php artisan migrate
- The table is been created and I added some records in it.
3. Model
Create 2 Models –
Departments –
php artisan make:model Departments
- Specify mass assignable Model attributes – name using the
$fillableproperty.
Completed Code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Departments extends Model
{
protected $fillable = [
'name'
];
}
Employees –
php artisan make:model Employees
- Specify mass assignable Model attributes – username, name, email, and department using the
$fillableproperty.
Completed Code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employees extends Model
{
protected $fillable = [
'username','name','email','department'
];
}
4. Controller
Create a DepartmentsController controller.
php artisan make:controller DepartmentsController
Import Departments and Employees Model.
Here, create two methods –
- index – Fetch all records from
departmentstable and assign in$departmentData['data'].
Load index view and pass $departmentData.
- getEmployees – This method used to handle the AJAX request. Fetch records from
employeestable where thedepartment = $departmentid.
Return $userData Array in JSON format.
Completed Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Departments;
use App\Employees;
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);
}
}
5. Route
Open routes/web.php file.
Here, define two routes –
- /
- /getEmployees/{id} – This route use in jQuery AJAX request to get employees list.
<?php
Route::get('/', 'DepartmentsController@index'); // localhost:8000/
Route::get('/getEmployees/{id}', 'DepartmentsController@getEmployees');
6. View
Create a new index.blade.php file in resources/views/ folder.
HTML –
Create two <select > elements –
- In the first
<select >display departments name by looping on$departmentData['data']. - The second
<select >is used to display employee names according to the selected department using jQuery.
jQuery –
Define change event on the first dropdown (<select id='sel_depart'>).
Read selected value and empty the second <select id='sel_emp'> element all options except first.
Send AJAX GET request to 'getEmployees/' and also pass id value.
On successful callback check response length if it is greater than 0 then loop on response. Create options and append in #sel_emp selector.
Completed Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<!-- Department Dropdown -->
Department : <select id='sel_depart' name='sel_depart'>
<option value='0'>-- Select department --</option>
<!-- Read Departments -->
@foreach($departmentData['data'] as $department)
<option value='{{ $department->id }}'>{{ $department->name }}</option>
@endforeach
</select>
<br><br>
<!-- Department Employees Dropdown -->
Employee : <select id='sel_emp' name='sel_emp'>
<option value='0'>-- Select Employee --</option>
</select>
<!-- Script -->
<script type='text/javascript'>
$(document).ready(function(){
// Department Change
$('#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>
7. Output
8. Conclusion
Define change event on the parent element and according to the selected value fetch records for child element with jQuery AJAX.
You can modify the code if you want to do this with more than two dropdowns. For this, you need to define change event accordingly and fetch records with jQuery AJAX.
You can view the Laravel 8 version of this tutorial here.
If you found this tutorial helpful then don't forget to share.