dolalima/query-string-helper

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

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/dolalima/query-string-helper

dev-main 2025-10-29 17:00 UTC

This package is auto-updated.

Last update: 2025-10-29 17:50:01 UTC


README

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

  • ๏ฟฝ 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

1. Install via Composer

composer require dolalima/query-string-helper

2. Add Service Provider (Laravel 5.0-5.4)

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)

Add the facade to your config/app.php:

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

4. Publish Configuration (Optional)

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

Development

Docker Development Environment

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

Prerequisites

  • Docker
  • Docker Compose

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

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

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

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

The library supports various operators for filtering:

Operator Description Example 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

Basic Filtering

GET /api/users?name=John&status=active
// Equivalent to: User::where('name', 'John')->where('status', 'active')

Advanced Filtering

GET /api/products?price$gte=10&price$lte=100&category$in=electronics,books
// Equivalent to: Product::where('price', '>=', 10)
//                       ->where('price', '<=', 100)
//                       ->whereIn('category', ['electronics', 'books'])

Relationship Filtering

GET /api/users?profile.age$gt=25&profile.city=NewYork
// Equivalent to: User::whereHas('profile', function($query) {
//                    $query->where('age', '>', 25)->where('city', 'NewYork');
//                })

Sorting

Use the order parameter to sort results:

GET /api/users?order=name,-created_at,+email
  • + or no prefix = ASC
  • - prefix = DESC

Field Selection

Select specific fields using the fields parameter:

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

Relationship Loading

Load relationships using the $with parameter:

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

Pagination

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

Advanced Usage

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

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

Force Pagination

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

Complete Example

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Dolalima\QueryStringHelper\QueryStringHelper;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $helper = new QueryStringHelper(
            $request,
            Product::class,
            [
                'active' => 1  // Only show active products
            ],
            ['category', 'tags'], // Eager load relationships
            'created_at'          // Default order by
        );

        $products = $helper->getResult();

        return response()->json($products);
    }
}

Example API calls:

GET /api/products?name$lk=%laptop%&price$bw=100,1000&category.name=Electronics&order=-price,+name&fields=id,name,price&page=1&per_page=10&$with=reviews

Reserved Parameters

The following parameters have special meanings and won't be treated as model filters:

  • sort - Alternative to order
  • fields - Field selection
  • page - Pagination page number
  • per_page - Items per page
  • count - Item count
  • random - Random ordering
  • limit - Result limit
  • $with - Relationship loading

Model Requirements

Your Eloquent models should implement a getMaps() method if you want to support field mapping:

class Product extends Model
{
    public static function getMaps()
    {
        return [
            'product_name' => 'name',  // Allow 'product_name' to map to 'name' field
            'product_price' => 'price'
        ];
    }
}

Configuration

The package automatically detects your model's table columns and relationships. You can customize behavior through the constructor parameters and optional parameters array.

API Reference

Constructor

new QueryStringHelper(
    Request $request,        // HTTP request object
    string $model,          // Model class name
    array $optionalParams,  // Additional filter conditions
    array $with,           // Default relationships to load
    string $orderBy        // Default order field
)

Core Methods

Method Description Returns
run() Execute all filters, sorting, and field selection void
getResult($forcePagination, $defaultPerPage) Get paginated or collection results LengthAwarePaginator|Collection
getQuery($pagination) Get the query builder instance Builder
runFilters() Apply query parameter filters void
runSort() Apply sorting parameters void
runFields() Apply field selection void
getQueryString() Get the parsed query parameters array
setQueryString($queryString) Set query parameters manually void

Testing

Local Testing

# Install dependencies
composer install

# Run tests
./vendor/bin/phpunit

# Run tests with coverage
./vendor/bin/phpunit --coverage-html coverage

Docker Testing

# Run tests in Docker
make test

# Run tests with coverage in Docker
make test-coverage

# Run specific test file
docker-compose run --rm phpunit tests/QueryStringHelperTest.php

# Run tests with filter
docker-compose run --rm phpunit --filter testCanParseUrl

Requirements

  • PHP >= 5.5.9
  • Laravel >= 5.0 (illuminate/support, illuminate/database, illuminate/http)
  • Eloquent ORM

License

This package is open-sourced software licensed under the MIT license.

Contributing

Please see CONTRIBUTING.md for details on how to contribute.

Changelog

Please see CHANGELOG.md for details on changes and updates.

Credits

Support

If you discover any security vulnerabilities, please send an e-mail via dolalima@gmail.com.

For general questions and support, please use the GitHub issues page.