- How do I install spatie/query-string in a Laravel project?
- Run `composer require spatie/query-string` in your project directory. The package requires PHP 7.4+ and has no Laravel-specific dependencies, so it integrates immediately without configuration.
- Can I use this package to toggle query parameters like debug flags in Laravel?
- Yes. Use `$queryString->toggle('debug')` to add or remove a parameter. For example, `/` becomes `/?debug=true` on first call, and `/?debug=true` becomes `/` on the second call.
- Does this package support Laravel 10 or newer?
- The package supports PHP 7.4+, which includes Laravel 10+. However, it hasn’t been updated since 2020, so test thoroughly with your Laravel version to ensure compatibility with newer features.
- How do I handle multi-value parameters like `?tags[]=php&tags[]=laravel`?
- Use the `toggle` method with the array syntax: `$queryString->toggle('tags[]', 'php')` adds `?tags[]=php`, and `$queryString->toggle('tags[]', 'laravel')` appends `&tags[]=laravel`. To remove a value, call it again.
- Is this package safe for user-controlled query strings in APIs?
- The package handles basic URL encoding, but for user input, validate parameters separately using Laravel’s `Validator` or `Str::of()` to prevent injection or malformed queries.
- Can I use this with Laravel’s Request object to modify incoming URLs?
- Yes. Instantiate the `QueryString` with `$request->fullUrl()`, modify it, then redirect or pass the updated URL to the frontend. Example: `$queryString->toggle('feature'); return redirect($queryString->toString());`
- Does it support JSON:API-style sorting (e.g., `?sort=-created_at`)?
- Yes. Use `$queryString->sort('created_at')` to toggle between `?sort=created_at` and `?sort=-created_at`. Only single sorts are supported at this time.
- How do I handle pagination with this package?
- Use `$queryString->page(2)` to set `?page=2`. The method automatically handles the `page` parameter, making it ideal for Laravel pagination links in APIs or admin panels.
- Are there alternatives to this package in Laravel’s ecosystem?
- Laravel’s built-in `Request` methods (e.g., `query()`, `merge()`) can handle simple cases, but this package excels for complex URL manipulation like toggling flags, JSON:API filters, or multi-value arrays without manual string parsing.
- How do I test this package in a Laravel application?
- Test with encoded query strings (e.g., `?param=hello%20world`) and Laravel’s `Request` object. Mock `$request->fullUrl()` in unit tests to verify parameter toggling, filtering, and sorting logic.