- How do I install spatie/laravel-query-builder in my Laravel project?
- Run `composer require spatie/laravel-query-builder` in your terminal. The package integrates automatically with Laravel’s service container, requiring no additional configuration.
- Can I use this package with Laravel 6 or older versions?
- The package officially supports Laravel 7 and newer. For older versions, you may need to check the package’s release history for compatibility or use a forked version, but this is not recommended.
- How do I restrict API clients from querying sensitive fields?
- Use the `allowedFilters()` method to specify which fields can be filtered. For example, `QueryBuilder::for(User::class)->allowedFilters(['name', 'email'])` ensures only those fields are queryable.
- Does this package support nested relationships in includes?
- Yes, you can include nested relationships by chaining them in the `include` parameter. For example, `?include=posts.comments` will load posts and their comments. Configure this via `allowedIncludes()`.
- How can I set default filter values for API requests?
- Use the `defaultFilter()` method to set default values. For example, `QueryBuilder::for(User::class)->defaultFilter('active', true)` will apply `where('active', true)` by default.
- Will this package work with existing Eloquent scopes in my application?
- Yes, the package integrates seamlessly with Eloquent scopes. You can use `allowedScopes()` to define which scopes are allowed in API requests, and they’ll be applied automatically.
- How do I prevent SQL injection when using dynamic filters?
- The package sanitizes all input by default, but you must explicitly allow fields via `allowedFilters()`. Only whitelisted fields will be used in queries, eliminating SQL injection risks.
- Can I use this package with Laravel’s API resources or GraphQL?
- Yes, the package is ideal for RESTful APIs and works alongside Laravel’s API resources. For GraphQL, you’d typically use it in resolvers to handle dynamic filtering and sorting.
- How do I handle complex custom filters, like date ranges or JSON fields?
- Use the `customFilter()` method to define custom logic. For example, `customFilter('date_range', fn($query, $value) => $query->whereBetween('created_at', $value))` lets clients filter by date ranges.
- What’s the best way to test queries built with this package?
- Use Laravel’s HTTP tests to simulate API requests with query parameters. Mock the `QueryBuilder` class if needed, and verify results with assertions on the returned models or JSON responses.