A powerful Laravel library for converting URL query parameters into Eloquent query conditions. Build dynamic, filterable APIs with ease! Compatible with Laravel 5.0+.
- � 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
composer require dolalima/query-string-helperFor Laravel 5.0-5.4, add the service provider to your config/app.php:
'providers' => [
// Other providers...
Dolalima\QueryStringHelper\QueryStringHelperServiceProvider::class,
],Add the facade to your config/app.php:
'aliases' => [
// Other aliases...
'QueryStringHelper' => Dolalima\QueryStringHelper\Facades\QueryStringHelper::class,
],php artisan vendor:publish --provider="Dolalima\QueryStringHelper\QueryStringHelperServiceProvider" --tag="config"This package includes a complete Docker development environment. You can use either Docker Compose directly or the provided helper scripts.
- Docker
- Docker Compose
-
Clone the repository
git clone https://github.com/dolalima/query-string-helper.git cd query-string-helper -
Copy environment file
cp .env.example .env
-
Build and install dependencies
make build make install
-
Run tests
make test
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 imagesUsing 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 upUsing Docker Compose directly:
docker-compose build
docker-compose run --rm composer install
docker-compose run --rm phpunit
docker-compose run --rm php bashThe 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.
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);
}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 |
GET /api/users?name=John&status=active
// Equivalent to: User::where('name', 'John')->where('status', 'active')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'])GET /api/users?profile.age$gt=25&profile.city=NewYork
// Equivalent to: User::whereHas('profile', function($query) {
// $query->where('age', '>', 25)->where('city', 'NewYork');
// })Use the order parameter to sort results:
GET /api/users?order=name,-created_at,+email
+or no prefix = ASC-prefix = DESC
Select specific fields using the fields parameter:
GET /api/users?fields=id,name,email
Load relationships using the $with parameter:
GET /api/users?$with=profile,posts,roles
GET /api/users?page=2&per_page=20
$helper = new QueryStringHelper(
$request,
User::class,
[
'active' => 1, // Always filter active users
['deleted_at' => null] // Custom where condition
],
['profile', 'roles']
);$query = $helper->getQuery();
$query->where('custom_condition', 'value');
$results = $query->get();$results = $helper->getResult(true, 25); // Force pagination with 25 per page<?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
The following parameters have special meanings and won't be treated as model filters:
sort- Alternative toorderfields- Field selectionpage- Pagination page numberper_page- Items per pagecount- Item countrandom- Random orderinglimit- Result limit$with- Relationship loading
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'
];
}
}The package automatically detects your model's table columns and relationships. You can customize behavior through the constructor parameters and optional parameters array.
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
)| 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 |
# Install dependencies
composer install
# Run tests
./vendor/bin/phpunit
# Run tests with coverage
./vendor/bin/phpunit --coverage-html coverage# 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- PHP >= 5.5.9
- Laravel >= 5.0 (illuminate/support, illuminate/database, illuminate/http)
- Eloquent ORM
This package is open-sourced software licensed under the MIT license.
Please see CONTRIBUTING.md for details on how to contribute.
Please see CHANGELOG.md for details on changes and updates.
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.