Dropdown Laravel 10 jQuery Ajax(Category SubCategory)
Creating Dependent Dropdowns Using Laravel 10 and jQuery Ajax(Category SubCategory)
Dependent dropdowns are a common feature in web development, allowing users to select options in one dropdown menu based on the selection made in another dropdown. This dynamic interaction enhances user experience and streamlines data selection processes. In this tutorial, we will explore how to implement dependent dropdowns using Laravel 10 and jQuery Ajax. By leveraging Laravel’s powerful features and the flexibility of jQuery Ajax, we can create seamless and responsive dropdown menus that adapt to user input, improving the overall usability of our web applications. Let’s dive in and learn how to implement this useful functionality in our Laravel projects.
Dependent dropdowns, also known as cascading dropdowns, are a crucial aspect of web development, particularly in scenarios where users need to select options based on the values of other related dropdowns. This dynamic interaction between dropdown menus enhances user experience by providing a more intuitive and efficient way to navigate through large sets of data or options.
In this tutorial, we will focus on implementing dependent dropdowns using Laravel 10 and jQuery Ajax. Laravel, a popular PHP framework, provides robust features for building web applications, while jQuery Ajax allows us to make asynchronous requests to the server, enabling seamless interaction between the frontend and backend.
The concept behind dependent dropdowns is straightforward: when a user selects an option from the first dropdown (parent dropdown), the options available in the second dropdown (child dropdown) are dynamically updated based on the selected value. This ensures that users only see relevant options, thereby simplifying the selection process and reducing the likelihood of errors.
To achieve this functionality in Laravel, we’ll follow these general steps:
- Set up the Laravel project: We’ll create a new Laravel project or use an existing one as the foundation for our application.
- Define database models and relationships: Depending on the data structure, we’ll define database tables and establish relationships between them using Laravel’s Eloquent ORM.
- Create routes and controller methods: We’ll define routes to handle Ajax requests and create controller methods to fetch data based on user input.
- Implement frontend logic with jQuery Ajax: On the frontend, we’ll use jQuery to capture user selections, send Ajax requests to the server, and update the child dropdown dynamically.
- Render dropdowns in the view: We’ll integrate the dynamic dropdown functionality into our views using Laravel’s Blade templating engine.
- Test and refine: Finally, we’ll thoroughly test the functionality to ensure that the dependent dropdowns work as expected, refining the implementation as needed.
Throughout the tutorial, we’ll provide detailed explanations, code snippets, and examples to guide you through each step of the process. By the end of this tutorial, you’ll have a solid understanding of how to implement dependent dropdowns in Laravel applications, empowering you to create more user-friendly and interactive web experiences. Let’s get started!
In this tutorial, we’ll explore how to dynamically display subcategories in a dropdown menu based on the selected category. While our focus will be on implementing this feature in Laravel 10, the concepts can be applied to any version of Laravel. Let’s dive into the steps below to create this dropdown example.
Step 1: Install laravel
Run the code below to install a new Laravel project, or alternatively, you can utilize an existing project.
composer create-project laravel/laravel dynamic-dropdown
Step 2: Connect Database, Model and Migration
Create a database and update your .env file with the newly created database information.
DB_DATABASE=dynamic-dropdown
DB_USERNAME=root
DB_PASSWORD=
In this step, we’ll generate models for Category and Subcategory along with two migration files using the -m
argument. Run the command below:
php artisan make:model Category -m
php artisan make:model SubCategory -m
Now update the migrations file as show bellow
categories_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};
subcategories_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('subcategories', function (Blueprint $table) {
$table->id();
$table->string('subcategory');
$table->bigInteger('category_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('subcategories');
}
};
Also update the Category and Subcategory models
Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['name'];
}
Subcategory.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
use HasFactory;
protected $fillable = ['name','category_id'];
}
Now run the bellow artisan command
php artisan migrate
Step 3 : Create route
We need to create two routes: one for displaying the dynamic dropdown page and another for fetching subcategories based on their categories.
Let’s define the necessary routes:
web.php
Route::get('dropdown',[DropdownController::class, 'dropdown'])->name('dropdown');
Route::post('subcategory',[DropdownController::class, 'subcategory'])->name('subcategory');
Step 6: Create Controller and Update
In this step we will create controller and update the controller with two methods for category and subcategories.
Run the command to create a controller:
php artisan make:controller DropdownController
Now Update the DropdownController like bellow
DropdownController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Subcategory;
class DropdownController extends Controller
{
//dropdown page view
public function dropdown()
{
$categories = Category::all();
return view('dropdown',compact('categories'));
}
//get subcategory
public function subcategory(Request $request)
{
$subcategories = Subcategory::where('category_id', $request->category)->get();
return response()->json([
'status' => 'success',
'subcategories' => $subcategories,
]);
}
}
Step 4 : Create Blade File
Next, we’ll create a Blade file to display our categories and dynamically update the subcategories when a category is changed.
Let’s create a new Blade file named dropdown.blade.php
and update it with the following code.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title> Dropdown</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form>
<h4 class="my5">Dynamic Dropdown</h4>
<div class="form-group my-3">
<label class="mb-1">Select Category</label>
<select name="name" id="category" class="form-control">
<option>Change Category</option>
@foreach($categories as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
@endforeach
</select>
</div>
<div class="form-group my-3">
<label class="mb-1">Select Subcategory</label>
<select name="name" id="subcategory" class="form-control subcategory"></select>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script>
$(document).ready(function(){
$(document).on('change','#category', function() {
let category = $(this).val();
$('#subcategory_info').show();
$.ajax({
method: 'post',
url: "{{ route('subcategory') }}",
data: {
category: category
},
success: function(res) {
if (res.status == 'success') {
let all_options = "<option value=''>Select Sub Category</option>";
let all_subcategories = res.subcategories;
$.each(all_subcategories, function(index, value) {
all_options += "<option value='" + value.id +
"'>" + value.name + "</option>";
});
$(".subcategory").html(all_options);
}
}
})
});
});
</script>
</body>
</html>
Run the server using the bellow command:
php artisan serve