Loading image

Blogs / Programming

How to Create a Dynamic Select2 Dropdown with Laravel and AJAX

How to Create a Dynamic Select2 Dropdown with Laravel and AJAX

  • showkat ali
  • 0 Comments
  • 15 View

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.

What is Select2?

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.

Step 1: Set Up Your Laravel Routes

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');

 

Step 2: Create Controller Methods to Fetch Data

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.

 

Step 3: Set Up the HTML with Data Attributes

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>

 

Step 4: Write a Generic jQuery Function to Initialize Select2 with AJAX

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
            }
        });
    });
});

 

Explanation of the Code

  • .select2-ajax Class: Targets all <select> elements with this class for Select2 initialization.
  • Data Attributes: Each <select> uses a data-url attribute to specify the URL for fetching data, making the function flexible.
  • Minimum Input Length: Set to 1 so the AJAX call only triggers after the user types at least one character.
  • AJAX Settings:
    • 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.

Benefits of This Generic Approach

  • Reusable: This function can be used for any dropdown just by adding the .select2-ajax class and data-url attribute.
  • Efficient: No need to write separate JavaScript for each dropdown, reducing code duplication.
  • Dynamic: Allows you to add more dropdowns with different endpoints by simply specifying the correct data-url in the HTML.

 

Final Thoughts

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.

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

How to Install Laravel 11 Globally : A Step-by-Step Guide

How to Install Laravel 11 Globally : A Step-by-Step Guide

showkat ali
/
Programming

Read More
Spatie's Role and Permission package in Laravel

Spatie's Role and Permission package in Laravel

Muhammad Abbas
/
Programming

Read More
The Rise of the First AI Software Engineer | devin cognition

The Rise of the First AI Software Engineer | devin cognition

showkat ali
/
Programming

Read More
How to Use Summernote in React.js: A Simple Guide

How to Use Summernote in React.js: A Simple Guide

showkat ali
/
Programming

Read More
PostgreSQL vs MySQL: Which Should You Use for Your Project

PostgreSQL vs MySQL: Which Should You Use for Your Project

showkat ali
/

Read More
How to Get a Job at Google: A Step-by-Step Guide

How to Get a Job at Google: A Step-by-Step Guide

showkat ali
/
Technology

Read More