Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Query String Laravel Package

crwlr/query-string

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require crwlr/query-string
    
  2. Basic Usage:

    use Crwlr\QueryString\Query;
    
    // From string
    $query = new Query('foo=bar&baz[]=qux');
    $array = $query->toArray(); // ['foo' => 'bar', 'baz' => ['qux']]
    
    // From array
    $query = new Query(['foo' => 'bar', 'baz' => ['qux']]);
    $string = $query->toString(); // 'foo=bar&baz%5B0%5D=qux'
    
  3. First Use Case: Parse and reconstruct query strings from Laravel Request objects:

    use Illuminate\Http\Request;
    use Crwlr\QueryString\Query;
    
    $requestQuery = new Query(request()->query->all());
    $modifiedQuery = $requestQuery->set('page', 2)->toString();
    

Where to Look First

  • Official Documentation for API reference.
  • Query class methods (set(), get(), has(), remove(), toArray(), toString()) for core functionality.
  • Changelog (v1.0.1–v1.0.3) to understand edge-case fixes (e.g., duplicate keys, malformed strings).

Implementation Patterns

Core Workflows

1. Request Handling

Parse Laravel Request query strings into structured arrays:

$query = new Query(request()->query->all());
$page = $query->get('page', 1); // Default fallback
$filters = $query->get('filter', []); // Nested arrays

2. URL Generation

Build query strings for redirects or API calls:

$query = new Query(['page' => 2, 'sort' => ['name', 'asc']]);
$url = route('products.index', ['query' => $query->toString()]);

3. Form Data Processing

Handle multi-select or repeated fields (e.g., tags[]=php&tags[]=laravel):

$query = new Query(request()->post());
$tags = $query->get('tags', []); // ['php', 'laravel']

4. API Client Integration

Normalize external query strings (e.g., Google Fonts):

$externalQuery = new Query('family=Roboto&family=Open+Sans');
$normalized = $externalQuery->toArray(); // ['family' => ['Roboto', 'Open Sans']]

Laravel-Specific Patterns

Service Provider Binding

Bind the Query class to Laravel’s container for global use:

// app/Providers/AppServiceProvider.php
use Crwlr\QueryString\Query;

public function register()
{
    app()->bind(Query::class, function () {
        return new Query(request()->query->all());
    });
}

Usage:

$query = app(Query::class);

Request Macros

Extend Laravel’s Request class with query string helpers:

// app/Providers/AppServiceProvider.php
use Illuminate\Http\Request;
use Crwlr\QueryString\Query;

public function boot()
{
    Request::macro('queryString', function () {
        return new Query($this->query->all());
    });
}

Usage:

$query = request()->queryString();
$page = $query->get('page', 1);

Form Request Validation

Validate query strings in Laravel’s FormRequest:

use Crwlr\QueryString\Query;
use Illuminate\Foundation\Http\FormRequest;

class ProductRequest extends FormRequest
{
    public function rules()
    {
        $query = new Query($this->query->all());
        return [
            'page' => ['required', 'integer', Rule::when(
                $query->has('sort'),
                fn () => 'max:100'
            )],
        ];
    }
}

Integration Tips

  • Preserve Order: Use toArray() with Query to maintain key-value order (unlike http_build_query).
  • Nested Arrays: Leverage PHP’s array syntax (foo[bar][]=baz) for complex structures.
  • URL Encoding: Automatically handled via toString() (e.g., spaces → + or %20).
  • Default Values: Use get() with fallback:
    $query->get('page', 1); // Returns 1 if 'page' is missing
    

Gotchas and Tips

Pitfalls

  1. Duplicate Keys Without Brackets:

    • Issue: foo=bar&foo=baz defaults to ['foo' => 'baz'] (last value wins).
    • Fix: Use [] notation (foo[]=bar&foo[]=baz) or rely on v1.0.2+ behavior (auto-converts to array).
    • Debug: Check toArray() output to verify structure.
  2. Malformed Strings:

    • Issue: Strings like &foo=bar or foo=bar& may cause parsing errors.
    • Fix: Use trim() or validate input:
      $query = new Query(trim($_GET['query']));
      
  3. Nested Array Indices:

    • Issue: foo[bar][]=baz may not serialize as expected in older versions.
    • Fix: Upgrade to v1.0.3+ and use explicit indices:
      $query->set('foo[bar][0]', 'baz');
      
  4. URL Encoding Inconsistencies:

    • Issue: toString() may encode + as %20 or (space).
    • Fix: Normalize before output:
      str_replace('+', ' ', $query->toString());
      

Debugging Tips

  • Inspect Raw Input:
    $query = new Query('foo=bar&baz[]=qux');
    dump($query->toArray()); // ['foo' => 'bar', 'baz' => ['qux']]
    
  • Compare String ↔ Array:
    $array = $query->toArray();
    $string = $query->toString();
    assert($query->fromString($string)->toArray() === $array);
    
  • Handle Edge Cases:
    // Empty values
    $query = new Query('foo='); // ['foo' => '']
    // Trailing &
    $query = new Query('foo=bar&'); // ['foo' => 'bar']
    

Configuration Quirks

  • No Global Config: The library is stateless; all behavior is method-driven.
  • PHP Version: Requires PHP 8.0+. Test with php -v before use.
  • Laravel Caching: If using Query in cached views, serialize with toArray():
    cache()->put('query', $query->toArray());
    

Extension Points

  1. Custom Encoder: Override URL encoding/decoding:
    $query = new Query(['foo' => 'bar baz'], [
        'encoder' => fn ($value) => str_replace(' ', '-', $value),
    ]);
    
  2. Array Normalization: Filter or transform arrays before serialization:
    $query = new Query(['foo' => null]);
    $string = $query->toString(); // 'foo=' (not omitted)
    
  3. Event Listeners: Extend Query with events (e.g., beforeSet, afterToString) via traits or decorators.

Performance Notes

  • Large Arrays: For >1000 keys, consider chunking or streaming toString().
  • Memory: toArray() loads the entire query into memory; use get() for selective access.
  • Benchmark: Compare against http_build_query/parse_str for critical paths:
    $time = microtime(true);
    $query->toString();
    echo microtime(true) - $time; // ~0.0001s for 100 keys
    

Laravel-Specific Gotchas

  • Request Override: Avoid overriding Request methods (e.g., query()) to prevent conflicts.
  • Route Model Binding: Use toArray() for query string parameters in routes:
    Route::get('/products', function (Query $query) {
        return Product::where('name', 'like', '%' . $query->get('search') . '%')->get();
    })->bind('query');
    
  • API Resources: Serialize Query objects in JSON responses:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php