PHPackages                             dolalima/query-string-helper - 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. [Database &amp; ORM](/categories/database)
4. /
5. dolalima/query-string-helper

ActiveLibrary[Database &amp; ORM](/categories/database)

dolalima/query-string-helper
============================

A Laravel library for converting URL query parameters into Eloquent query conditions with advanced filtering, sorting, and relationship support

00PHP

Since Oct 29Pushed 6mo agoCompare

[ Source](https://github.com/dolalima/query-string-helper)[ Packagist](https://packagist.org/packages/dolalima/query-string-helper)[ RSS](/packages/dolalima-query-string-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

QueryStringHelper
=================

[](#querystringhelper)

A powerful Laravel library for converting URL query parameters into Eloquent query conditions. Build dynamic, filterable APIs with ease! Compatible with Laravel 5.0+.

Features
--------

[](#features)

- � **Advanced Query Filtering** - Support for multiple operators (eq, ne, gt, lt, like, between, in)
- 🔗 **Relationship Filtering** - Filter through model relationships using dot notation
- 📊 **Smart Sorting** - Multi-field sorting with ascending/descending options
- 📋 **Field Selection** - Choose specific fields to return in queries
- 🔄 **Eager Loading** - Automatically load relationships with field selection
- � **Pagination Support** - Built-in pagination with customizable per-page limits
- ⚙️ **Configurable** - Custom optional parameters and query conditions
- 🎯 **Laravel Integration** - Service provider, facade, and configuration support
- 🧪 **Well Tested** - Comprehensive test suite
- 📦 **Laravel 5.0+ Compatible** - Works with Laravel 5.0 and newer versions

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

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require dolalima/query-string-helper
```

### 2. Add Service Provider (Laravel 5.0-5.4)

[](#2-add-service-provider-laravel-50-54)

For Laravel 5.0-5.4, add the service provider to your `config/app.php`:

```
'providers' => [
    // Other providers...
    Dolalima\QueryStringHelper\QueryStringHelperServiceProvider::class,
],
```

### 3. Add Facade (Optional)

[](#3-add-facade-optional)

Add the facade to your `config/app.php`:

```
'aliases' => [
    // Other aliases...
    'QueryStringHelper' => Dolalima\QueryStringHelper\Facades\QueryStringHelper::class,
],
```

### 4. Publish Configuration (Optional)

[](#4-publish-configuration-optional)

```
php artisan vendor:publish --provider="Dolalima\QueryStringHelper\QueryStringHelperServiceProvider" --tag="config"
```

Development
-----------

[](#development)

### Docker Development Environment

[](#docker-development-environment)

This package includes a complete Docker development environment. You can use either Docker Compose directly or the provided helper scripts.

#### Prerequisites

[](#prerequisites)

- Docker
- Docker Compose

#### Quick Start

[](#quick-start)

1. **Clone the repository**

    ```
    git clone https://github.com/dolalima/query-string-helper.git
    cd query-string-helper
    ```
2. **Copy environment file**

    ```
    cp .env.example .env
    ```
3. **Build and install dependencies**

    ```
    make build
    make install
    ```
4. **Run tests**

    ```
    make test
    ```

#### Available Commands

[](#available-commands)

**Using Make (Recommended):**

```
make help          # Show available commands
make build         # Build Docker images
make install       # Install Composer dependencies
make test          # Run PHPUnit tests
make test-coverage # Run tests with coverage report
make shell         # Open interactive shell
make composer      # Run composer commands (e.g., make composer cmd="require package")
make up            # Start containers in background
make down          # Stop containers
make logs          # Show container logs
make clean         # Clean up containers and images
```

**Using Helper Script:**

```
./scripts/dev.sh help        # Show available commands
./scripts/dev.sh build       # Build Docker images
./scripts/dev.sh install     # Install dependencies
./scripts/dev.sh test        # Run tests
./scripts/dev.sh shell       # Open shell
./scripts/dev.sh composer    # Run composer commands
./scripts/dev.sh clean       # Clean up
```

**Using Docker Compose directly:**

```
docker-compose build
docker-compose run --rm composer install
docker-compose run --rm phpunit
docker-compose run --rm php bash
```

Usage
-----

[](#usage)

The QueryStringHelper is designed to work with Laravel Eloquent models, automatically converting URL query parameters into Eloquent query conditions. It supports filtering, sorting, field selection, and relationship loading.

### Basic Usage

[](#basic-usage)

```
use Dolalima\QueryStringHelper\QueryStringHelper;
use App\Models\User;

// In your controller
public function index(Request $request)
{
    $helper = new QueryStringHelper(
        $request,           // Request object
        User::class,        // Model class
        [],                 // Optional parameters
        ['profile'],        // Relations to eager load
        'id'               // Default order by field
    );

    // Get paginated results
    $users = $helper->getResult();

    return response()->json($users);
}
```

### Query Parameter Operators

[](#query-parameter-operators)

The library supports various operators for filtering:

OperatorDescriptionExample URL`eq` (default)Equals`?name=John``ne`Not equals`?status$ne=inactive``gt`Greater than`?age$gt=18``gte`Greater than or equal`?age$gte=21``lt`Less than`?price$lt=100``lte`Less than or equal`?price$lte=50``lk`Like (partial match)`?name$lk=%john%``bw`Between`?age$bw=18,65``in`In array`?status$in=active,pending`### Examples

[](#examples)

#### Basic Filtering

[](#basic-filtering)

```
GET /api/users?name=John&status=active

```

```
// Equivalent to: User::where('name', 'John')->where('status', 'active')
```

#### Advanced Filtering

[](#advanced-filtering)

```
GET /api/products?price$gte=10&price$lte=100&category$in=electronics,books

```

```
// Equivalent to: Product::where('price', '>=', 10)
//                       ->where('price', '', 25)->where('city', 'NewYork');
//                })
```

### Sorting

[](#sorting)

Use the `order` parameter to sort results:

```
GET /api/users?order=name,-created_at,+email

```

- `+` or no prefix = ASC
- `-` prefix = DESC

### Field Selection

[](#field-selection)

Select specific fields using the `fields` parameter:

```
GET /api/users?fields=id,name,email

```

### Relationship Loading

[](#relationship-loading)

Load relationships using the `$with` parameter:

```
GET /api/users?$with=profile,posts,roles

```

### Pagination

[](#pagination)

```
GET /api/users?page=2&per_page=20

```

### Advanced Usage

[](#advanced-usage)

#### Custom Optional Parameters

[](#custom-optional-parameters)

```
$helper = new QueryStringHelper(
    $request,
    User::class,
    [
        'active' => 1,                    // Always filter active users
        ['deleted_at' => null]            // Custom where condition
    ],
    ['profile', 'roles']
);
```

#### Getting Query Builder

[](#getting-query-builder)

```
$query = $helper->getQuery();
$query->where('custom_condition', 'value');
$results = $query->get();
```

#### Force Pagination

[](#force-pagination)

```
$results = $helper->getResult(true, 25); // Force pagination with 25 per page
```

### Complete Example

[](#complete-example)

```
