PHPackages                             teguh02/laravel-select2-ajax - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. teguh02/laravel-select2-ajax

ActiveLibrary[API Development](/categories/api)

teguh02/laravel-select2-ajax
============================

Laravel API Backend for Select2 Ajax

1.4(1y ago)0123MITPHPPHP ^8.0CI passing

Since Jun 13Pushed 1y agoCompare

[ Source](https://github.com/teguh02/Laravel-Select2-Ajax)[ Packagist](https://packagist.org/packages/teguh02/laravel-select2-ajax)[ Docs](https://github.com/teguh02/laravel-select2-ajax)[ RSS](/packages/teguh02-laravel-select2-ajax/feed)WikiDiscussions main Synced today

READMEChangelog (5)Dependencies (2)Versions (6)Used By (0)

Laravel Select2 Ajax API Backend
================================

[](#laravel-select2-ajax-api-backend)

A simple, flexible, and reusable backend API for [Select2](https://select2.org/) AJAX dropdowns in Laravel.

Features
--------

[](#features)

- Dynamic model and field configuration via config file
- Supports search, filtering, and custom where clauses
- Caching support for improved performance
- Pagination/limit support
- Easy integration with Select2 frontend

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require teguh02/laravel-select2-ajax
```

Publish the configuration file:

```
php artisan vendor:publish --provider="TeguhRijanandi\LaravelSelect2Ajax\LaravelSelect2AjaxServiceProvider"
```

1. **Register the service provider and routes as needed.**
2. **Publish the configuration file (if available).**

Configuration
-------------

[](#configuration)

Configure your searchable models and fields in `config/select2-ajax.php`:

```
return [
    'query' => [
        // Example:
        \App\Models\User::class => [
            'id' => 'id', // The field that will be used as the id in the response.
            'text' => 'name', // The field that will be used as the text in the response.
            'searchable' => ['name', 'email'], // The fields that will be used for searching.
            // Optional:
            // 'order_by' => 'name', // The field that will be used for ordering the results.
            // 'where' => fn($query) => $query->where('active', 1), // The where clause for the query.
        ],
        // Add more models as needed...
    ],
    'result_limit' => 10,
    'cache_ttl' => 60, // seconds, 0 = no cache
];
```

**Configuration Attributes Guide:**

- **search\_url**
    The URL for the Select2 search API endpoint.
    Default: `/select2/search`
    Set via `SELECT2_SEARCH_URL` in your `.env` file.
- **search\_route\_name**
    The route name for the Select2 search API endpoint.
    Default: `select2.search`
    Set via `SELECT2_SEARCH_ROUTE_NAME` in your `.env` file.
- **result\_limit**
    The maximum number of results returned by the search query.
    Default: `10`
    Set via `SELECT2_RESULT_LIMIT` in your `.env` file.
- **query**
    The configuration for each model you want to make searchable.
    Each model config supports:

    - `id`: The field used as the id in the response.
    - `text`: The field used as the text in the response.
    - `searchable`: The fields used for searching.
    - `order_by`: The fields used for ordering the results. Example: `['name' => 'asc']`
    - `where`: The where clause for the query. Can be `null` or a closure for custom filtering.

    **Example:**

    ```
    'query' => [
        \App\Models\User::class => [
            'id' => 'id',
            'text' => 'name',
            'searchable' => ['name', 'email'],
            'order_by' => ['name' => 'asc'],
            'where' => null,
            // 'where' => function ($query) {
            //     return $query->whereNotNull('email_verified_at');
            // },
        ],
        // Add more models as needed
    ],
    ```
- **cache\_ttl**
    The cache time-to-live (TTL) in minutes for search results.
    Set to `0` to disable caching.
    Default: `60`
- **middleware**
    The middleware(s) applied to the Select2 search API route.
    Default: `['api']`
    You can customize this to add authentication or other middleware as needed.

Usage
-----

[](#usage)

### API Endpoint

[](#api-endpoint)

Send a GET or POST request to the endpoint (e.g. `/api/select2/search`) with the following parameters:

- `q` (string): The search term entered by the user.
- `query` (string): The model key as configured (e.g. `User`).

**Example Request:**

```
GET /api/select2/search?q=john&query=User
```

**Example Response:**

```
{
  "data": [
    { "id": 1, "text": "John Doe" },
    { "id": 2, "text": "Johnny Appleseed" }
  ]
}
```

### Frontend Integration

[](#frontend-integration)

Configure your Select2 input to use AJAX, for example:

```
$('#your-select').select2({
    ajax: {
        url: '/api/select2/search',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                query: 'User' // or your configured model key
            };
        },
        processResults: function (data) {
            return {
                results: data.data
            };
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // see the HTTP Codes guide in package documentation
            if (jqXHR.status === 400) {
                alert('Invalid query type.');
            } else if (jqXHR.status === 404) {
                alert('Model configuration not found.');
            } else if (jqXHR.status === 500) {
                alert('Unexpected server error. Please check the logs.');
            } else {
                alert('An unknown error occurred.');
            }
        }
    }
});
```

Advanced
--------

[](#advanced)

- **Custom Filtering:**
    Use the `where` closure in config for custom query logic.
- **Caching:**
    Set `cache_ttl` in config to cache results for faster repeated queries.
- **Result Limit:**
    Adjust `result_limit` in config to control how many results are returned.

HTTP Codes
----------

[](#http-codes)

- **200**: Success, data returned as expected.
- **400**: The query type is invalid.
- **404**: The model configuration is missing.
- **500**: Unexpected errors (see Laravel logs for details).

License
-------

[](#license)

MIT or your preferred license.

Contributing
------------

[](#contributing)

Contributions are welcome! To contribute to this library:

1. **Fork the repository** and create your branch from `main`.
2. **Make your changes** with clear commit messages.
3. **Test your changes** to ensure nothing is broken.
4. **Submit a pull request** describing your changes and why they should be merged.

If you find a bug or have a feature request, please open an issue.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance48

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

5

Last Release

386d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/86437a73401dd2749be2dcae882e8a9937fe5dcd6b0d8895e5358c697f6a1898?d=identicon)[teguh02](/maintainers/teguh02)

---

Top Contributors

[![teguh02](https://avatars.githubusercontent.com/u/43981051?v=4)](https://github.com/teguh02 "teguh02 (15 commits)")

---

Tags

apilaravelajaxdropdownselect2TeguhRijanandi

### Embed Badge

![Health badge](/badges/teguh02-laravel-select2-ajax/health.svg)

```
[![Health](https://phpackages.com/badges/teguh02-laravel-select2-ajax/health.svg)](https://phpackages.com/packages/teguh02-laravel-select2-ajax)
```

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M101](/packages/dedoc-scramble)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.9k3](/packages/defstudio-telegraph)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[lettermint/lettermint-laravel

Official Lettermint driver for Laravel

1190.2k1](/packages/lettermint-lettermint-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
