How to Use Quill Rich Text Editor in React JS | 2024
Read More
Dynamic dropdowns can enhance user experience by providing options only when needed, reducing page load time and complexity. In this guide, we’ll use Laravel and AJAX to create a dynamic Select2 dropdown that fetches data from the backend as users type. We’ll also make the function generic, so it can be reused across multiple dropdowns by specifying different endpoints.
Select2 is a jQuery-based replacement for standard select elements, offering features like search, dynamic loading, and multi-selection. Select2’s AJAX support allows dropdown options to be fetched from the server on demand, which is perfect for cases where we have a large dataset or multiple dropdowns.
To fetch data for each dropdown, we’ll define routes in web.php
that point to controller methods responsible for fetching the data.
// routes/web.php
Route::get('/search/projects', [SearchController::class, 'searchProjects'])->name('search.projects');
Route::get('/search/tasks', [SearchController::class, 'searchTasks'])->name('search.tasks');
Route::get('/search/employees', [SearchController::class, 'searchEmployees'])->name('search.employees');
In your controller (e.g., SearchController
), create methods for each type of data that return JSON responses. This ensures that each Select2 dropdown fetches data dynamically.
// app/Http/Controllers/SearchController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Project;
use App\Models\Task;
use App\Models\Employee;
class SearchController extends Controller
{
public function searchProjects(Request $request)
{
$query = $request->input('q');
$results = Project::where('name', 'LIKE', "%{$query}%")
->take(10)
->get(['id', 'name']);
return response()->json($results);
}
public function searchTasks(Request $request)
{
$query = $request->input('q');
$results = Task::where('title', 'LIKE', "%{$query}%")
->take(10)
->get(['id', 'title as name']); // Renaming 'title' to 'name' for consistency
return response()->json($results);
}
public function searchEmployees(Request $request)
{
$query = $request->input('q');
$results = Employee::where('name', 'LIKE', "%{$query}%")
->take(10)
->get(['id', 'name']);
return response()->json($results);
}
}
Each method takes a search term (q
) from the request, queries the relevant model, and returns a JSON response. Here, we use the id
and name
fields, which Select2 expects.
Now, in your Blade template, set up the <select>
elements with a common class (select2-ajax
) and unique data-url
attributes pointing to each endpoint. This lets you dynamically specify which endpoint to use for each dropdown without repeating code.
<select class="form-control select2-ajax" data-url="{{ route('search.projects') }}" name="project_id" required>
<option value="">Select Project</option>
</select>
<select class="form-control select2-ajax" data-url="{{ route('search.tasks') }}" name="task_id" required>
<option value="">Select Task</option>
</select>
<select class="form-control select2-ajax" data-url="{{ route('search.employees') }}" name="employee_id" required>
<option value="">Select Employee</option>
</select>
Here’s where the magic happens! Instead of writing separate jQuery code for each <select>
, we’ll create a generic function to initialize all elements with the .select2-ajax
class.
$(document).ready(function () {
$('.select2-ajax').each(function () {
$(this).select2({
placeholder: $(this).find('option:first').text(), // Use the first option as placeholder
minimumInputLength: 1, // Minimum characters before search starts
ajax: {
url: $(this).data('url'), // Fetch the URL from data-url attribute
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // Pass search term as 'q'
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.id,
text: item.name // Assumes each item has 'id' and 'name' fields
};
})
};
},
cache: true
}
});
});
});
.select2-ajax
Class: Targets all <select>
elements with this class for Select2 initialization.<select>
uses a data-url
attribute to specify the URL for fetching data, making the function flexible.1
so the AJAX call only triggers after the user types at least one character.url
: Reads the data-url
attribute to know which endpoint to hit.data
: Sends the search term (params.term
) as q
to the backend.processResults
: Maps the returned data to the format expected by Select2, using id
and name
..select2-ajax
class and data-url
attribute.data-url
in the HTML.With this approach, you can create powerful, dynamic dropdowns in Laravel that load options based on user input. This not only optimizes performance but also makes your codebase cleaner and easier to maintain. By leveraging Laravel’s backend and Select2’s AJAX capabilities, you can build a more responsive and user-friendly interface for your application.
Recent posts form our Blog
0 Comments
Like 0