PHPackages                             dorvidas/laravel-query-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. dorvidas/laravel-query-builder

ActiveLibrary[API Development](/categories/api)

dorvidas/laravel-query-builder
==============================

Easily build Eloquent queries from API requests

v0.0.3(7y ago)05MITPHPPHP ^7.1

Since Mar 6Pushed 7y ago1 watchersCompare

[ Source](https://github.com/dorvidas/laravel-query-builder)[ Packagist](https://packagist.org/packages/dorvidas/laravel-query-builder)[ RSS](/packages/dorvidas-laravel-query-builder/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (7)Versions (4)Used By (0)

Easily build Eloquent queries from API requests
===============================================

[](#easily-build-eloquent-queries-from-api-requests)

[![Build Status](https://camo.githubusercontent.com/9d980263d17df1422f75facb55c13deb75ede27e5b9cca753a79a588ee2a6ac1/68747470733a2f2f7472617669732d63692e6f72672f646f7276696461732f6c61726176656c2d71756572792d6275696c6465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/dorvidas/laravel-query-builder)[![Latest Stable Version](https://camo.githubusercontent.com/8f1e1418e277457c4fa0ebe019706bbcd4c86239ffb84c2c49a5e03f6722a3dd/68747470733a2f2f706f7365722e707567782e6f72672f646f7276696461732f6c61726176656c2d71756572792d6275696c6465722f762f737461626c65)](https://packagist.org/packages/dorvidas/laravel-query-builder)[![Total Downloads](https://camo.githubusercontent.com/af5eb5f261b2150be603486e2ea57dbabc783a01f33f55d29f74f957841897b3/68747470733a2f2f706f7365722e707567782e6f72672f646f7276696461732f6c61726176656c2d71756572792d6275696c6465722f646f776e6c6f616473)](https://packagist.org/packages/dorvidas/laravel-query-builder)[![License](https://camo.githubusercontent.com/ef652760064c8180544d915713e4076910c9c83612d0a0d430cb6817c3e7563d/68747470733a2f2f706f7365722e707567782e6f72672f646f7276696461732f6c61726176656c2d71756572792d6275696c6465722f6c6963656e7365)](https://packagist.org/packages/dorvidas/laravel-query-builder)

This package allows you to filter and include eloquent relations based on a request. Filtering is possible even on relations. Query parameter names follow the [JSON API specification](https://jsonapi.org/) as closely as possible.

Basic usage
-----------

[](#basic-usage)

Filtering an API request by checking if column equals to value: `/users?filter[eq:active]=1` or `/users?filter[active]=1`(if no filter defined, the default `eq` filter is used):

```
$users = User::buildFromRequest()
    ->get();
// all `User`s that with columns `active` equal to 1
```

Requesting filtered relations from an API request: `/users?filter[posts.eq:published]=1&include=posts`:

```
$users = User::buildFromRequest()
    ->get();
// all `User`s with their published `posts` loaded
```

Requesting deep relations filtered from an API request: `/users?filter[posts.comments.eq:approved=1&include=posts.comments`:

```
$users = User::buildFromRequest()
    ->get();
// all `User`s with their `posts` and post `comments` that are approved
```

Works together nicely with existing queries, because `buildFromRequest` is basically Eloquent macro: `/users?filter[eq:name]=John`:

```
$users = User::buildFromRequest()
    ->where('active', 1)
    ->get();
// all `User`s whose name is `John` also enforcing them to be active users
```

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require dorvidas/laravel-query-builder
```

You can optionally publish the config file with:

```
php artisan vendor:publish --provider="Dorvidas\QueryBuilder\QueryBuilderServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

### Filters

[](#filters)

#### Out-of-box filters

[](#out-of-box-filters)

There are number of out-of-box filters that can be used right away. Filters are listed in config:

```
    'filters' => [
        'eq' => \Dorvidas\QueryBuilder\Filters\EqFilter::class,//Equals
        'neq' => \Dorvidas\QueryBuilder\Filters\NotEqFilter::class,//Not equals
        'in' => \Dorvidas\QueryBuilder\Filters\InFilter::class,// In
        'nin' => \Dorvidas\QueryBuilder\Filters\NotInFilter::class, //Not in
        'gt' => \Dorvidas\QueryBuilder\Filters\GreaterThanFilter::class,//Greater than
        'gte' => \Dorvidas\QueryBuilder\Filters\GreaterThanEqualFilter::class,//Greater than equals
        'lt' => \Dorvidas\QueryBuilder\Filters\LowerThanFilter::class,//Less than
        'lte' => \Dorvidas\QueryBuilder\Filters\LowerThanEqualFilter::class,//Less that equals
        'like' => \Dorvidas\QueryBuilder\Filters\LikeFilter::class,//Like
        'nlike' => \Dorvidas\QueryBuilder\Filters\NotLikeFilter::class,//Not like
        'n' => \Dorvidas\QueryBuilder\Filters\NullFilter::class,//Null
        'nn' => \Dorvidas\QueryBuilder\Filters\NotNullFilter::class,//Not null
    ],
```

#### Using filters in URL

[](#using-filters-in-url)

JSON:API is agnostic to filtering strategy. The only requirement that filter would be placed in `&filter` query param. Proposed filter format:

- `&filter[eq:id]=1` - Column `id` equals 1. The part after semicolon is called filter attributes. Can have multiple if filter requires `&filter[between:from,to]=2018,2019`.
- `&filter[posts.eq:id]=1` - define filter for relation `posts`. If relation is deep we define full path to it `posts.comments.eq:id=1`.

#### Create filters

[](#create-filters)

If you need to create custom filter append the config.

```
'filters' => [
     /* ... */
    'recent' => \App\Filters\RecentFilter::class,
```

Filter should implement ` Dorvidas\QueryBuilder\FiltersFilterInterface` interface. Example filter:

```
use Carbon\Carbon;
use Dorvidas\QueryBuilder\Filters\FilterInterface;

class RecentFilter implements FilterInterface
{
    public function apply($query, $value, $params)
    {
        $col = isset($params[0]) ? $params[0] : 'created_at';
        $query->where($col, '>', Carbon::now()->subDay($value)->toDateTimeString());
    }
}
```

#### GOTCHAs

[](#gotchas)

Filters with no values are not applied i.e `$filter[eq:id]=`. Laravel application converts empty query params to `null` values by using `\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class` middleware and to filter rows where columns is `null` use `n:your_col=1` filter. Reason for that is when using documentation tools like Swagger I list all possible filters for endpoint and when value is not present I want to skip it.

### Including relations

[](#including-relations)

JSON:API allows request for [related resources](https://jsonapi.org/format/#fetching-includes). This is done via `include` query param i.e. `/users?include=posts`:

```
$users = User::buildFromRequest()
    ->get();
// all `User`s with their `posts`
// User model needs to have relation `posts`
```

#### Include constraints

[](#include-constraints)

It is possible to add constraints on which includes are allowed. Without it you can request for everything as long as there are requested relation defined i.e. `/users?include=posts`:

```
//This is fine
$users = User::buildFromRequest((new Constraints())->allowIncludes(['posts']))
    ->get();

//This is also fine
$users = User::buildFromRequest((new Constraints())->allowIncludes(['posts.comments']))
    ->get();

// This will throw `IncludeNotAllowedException` exception because no relations allowed
$users = User::buildFromRequest((new Constraints())->allowIncludes([]))
    ->get();
```

### Manually building query

[](#manually-building-query)

It is also possible to build query manually by using `buildFromArray` macro and passing instance of `\Dorvidas\QueryBuilder\ArrayBuilder` to it:

```
$items = App\User::buildFromArray(
    (new \Dorvidas\QueryBuilder\ArrayBuilder)
        ->filters([
            'in:id' => [1, 2]
        ])
        ->includes([
            'posts' => ['eq:active' => 1],
            'posts.owner' => [], //no filters
            'posts.comments' => ['eq:approved' => 1],
            'posts.comments.owner' => [],
        ])
    )->get();
```

### Sparse fields - TODO

[](#sparse-fields---todo)

### Sorting - TODO

[](#sorting---todo)

### Paginating - TODO

[](#paginating---todo)

### Limit results - TODO

[](#limit-results---todo)

### Testing

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

2624d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/61196e3395ce51576cd0bdfefca7c63ef2d4f763ddb441b414324c3eeb6f0e66?d=identicon)[dorvidas](/maintainers/dorvidas)

---

Top Contributors

[![dorvidas](https://avatars.githubusercontent.com/u/3006552?v=4)](https://github.com/dorvidas "dorvidas (8 commits)")

---

Tags

laravel-query-builderJSON-API

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dorvidas-laravel-query-builder/health.svg)

```
[![Health](https://phpackages.com/badges/dorvidas-laravel-query-builder/health.svg)](https://phpackages.com/packages/dorvidas-laravel-query-builder)
```

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[laravel-json-api/eloquent

Serialize Eloquent models as JSON:API resources.

121.4M4](/packages/laravel-json-api-eloquent)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[laravel-json-api/core

Contracts and support classes for Laravel JSON:API packages.

101.5M8](/packages/laravel-json-api-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
