PHPackages                             plokko/resource-query - 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. [Database &amp; ORM](/categories/database)
4. /
5. plokko/resource-query

ActiveLibrary[Database &amp; ORM](/categories/database)

plokko/resource-query
=====================

0.2.7(10mo ago)233031PHPPHP &gt;=7.2

Since May 11Pushed 10mo ago1 watchersCompare

[ Source](https://github.com/plokko/resource-query)[ Packagist](https://packagist.org/packages/plokko/resource-query)[ RSS](/packages/plokko-resource-query/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (8)Dependencies (1)Versions (9)Used By (1)

Resource-query
==============

[](#resource-query)

Automatic filtering and sorting for Laravel queries with Ajax capabilities.

Scope of this package
---------------------

[](#scope-of-this-package)

This package adds classes that help automate the creation of back-end defined user queries (Ajax) with advanced functions like filtering, sorting, pagination, resource casting and smart casting. The query will be based on a pre-defined Eloqent query and the user may customize the query by applying pre-defined query parameters. All the query parameters are easly defined and customized in the back-end allowing strict control on what the user can see or do.

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

[](#installation)

Install it via composer `composer require plokko/resource-query`

Initialization
--------------

[](#initialization)

To use this class you must extend the base `ResourceQuery` class or use a builder. Exending `ResourceQuery` class is preferred if you plan to reutilize the same settings, the builder approach is quicker if you plan to use it one time only.

### Extending ResourceQuery

[](#extending-resourcequery)

Create a new class that extends `plokko\ResourceQuery\ResourceQuery` and implement the function `getQuery()` that will return the base query

```
use plokko\ResourceQuery\ResourceQuery;

class ExampleResourceQuery extends ResourceQuery{

    protected function getQuery():Builder {
        // Return the base query
        return MyModel::select('id','a','b')
                ->where('fixed_condition',1);
    }

}
```

### Using the builder

[](#using-the-builder)

Or by defining it in-place with `ResourceQueryBuilder`

```
use plokko\ResourceQuery\ResourceQueryBuilder;

$query = MyModel::select('id','etc');
//Add the base query
$resource =  new ResourceQueryBuilder($query);
```

Example usage
-------------

[](#example-usage)

```
class MyController extends Controller {
    //...
    public function example1(Request $request){
        $resource = new ExampleResourceQuery();
        if($request->ajax()){
            return $resource;
        }
        view('example',compact('resource'));
    }
    public function example2(Request $request){
        $query = MyModel::select('id','etc');
        $resource =  new ResourceQueryBuilder($query);

        if($request->ajax()){
            return $resource;
        }
        view('example',compact('resource'));
    }
    //...
}
```

Adding filters
--------------

[](#adding-filters)

Filters are composed of a filter name (request query parameter associated with the filter), a condition used to parse the filters and a (optional) field name used to specify the table field to apply the filter to.

The condition can be either a base query condition (like `=`,`!=`,``,`like`,`in`, etc.), a shortand helper like `like%`,`%like` or `%like%` that will add a "%" character before, after or at both ends of the input or a Callable function that will resolve the filter. To the Callable filter will be passed 3 parameters: 0. \\Illuminate\\Database\\Query\\Builder|\\Illuminate\\Database\\Eloquent\\Builder query - The query where to apply the filter

1. mixed $value - The filtered value
2. FilterCondition $condition - The current condition, used to retrive condition or field name, etc.

You can add the filter in many ways:

```
// With the add function (default)
$resource->filters->add(,[],[]);
// Called as a parameter
$resource->filters->;
// Accessed as an array
$resource->filters[''];
// Called as a function
$resource->filters->([],[]);
```

You can also define or modifiy filter conditions or field name with the `condition` or `field` functions, ex:

```
$resource->filters->add('filter1')->condition('=')->field('fieldA');
$resource->filters->filter2->condition('like')->field('fieldB');
```

You can remove a filter with

```
$resource->filters->remove('');
```

or with unset function

```
unset($resource->filters['']);
```

If you wish to remove all filters use `php $resource->removeFilters();`

### Filter definition

[](#filter-definition)

Filters can be added either during class inizialization (if extended ResourceQuery)

```
class MyClassResource extends ResourceQuery{
    //...
    function __construct() {
        //Remember to call parent constructor for inizialization
        parent::__construct();
        // Adding filters
        $this->filter('filter1','=','fieldA');
        $this->filter('filter2','like','fieldB');
        //...
    }
    //...
}
```

Or by directly calling the resource

```
$query = MyModel::select('id','etc');
$resource =  new ResourceQueryBuilder($query);
// Note: this works also with already defined classes by adding or replacing existing filters
// Ex. replace lines above with: $resource = new ExampleResourceQuery();
$resource->filters->add('filter1','=','fieldA');
$resource->filters->add('filter2','like','fieldB');
```

### Filter root name

[](#filter-root-name)

If you want to encapsulate all your filter in an array (ex. "url?filter\[filter-name\]=value" ) you can define it with `setFiltersRoot`

```
$resource->setFiltersRoot('filter');//filters->add('filter1','=','fieldA')->defaultValue('1234');//If filter "filter1" is not set it will be applied with value "123"
```

#### Value formatting

[](#value-formatting)

If you want to format the filter value (ex. escaping characters, capitalize, etc.) before the filter is applied you can add a callable function with the `formatValue` function. The original filter value will be passed as a parameter and the return value will be used as the new filter value.

Example:

```
$resource->filters->add('filter1','=','fieldA')->formatValue(function($value){ return trim($value); });
```

#### Apply only if another filter is present

[](#apply-only-if-another-filter-is-present)

If you want to apply a filter ONLY if one or more filters are present you can use `applyIfPresent` function

```
$resource->filters->add('filter1','=','fieldA');
$resource->filters->add('filter2','like','fieldB');
// If fitler1 or filter2 are empty fitler3 will be ignored
$resource->filters->add('filter3','=','fieldC')->applyIfPresent('filter1','filter2');
```

#### Apply only if another filter is absent

[](#apply-only-if-another-filter-is-absent)

If you want to apply a filter ONLY if one or more filters are absent you can use `applyIfNotPresent` function

```
$resource->filters->add('filter1','=','fieldA');
$resource->filters->add('filter2','like','fieldB');
// If fitler1 or filter2 are not empty fitler3 will be ignored
$resource->filters->add('filter3','=','fieldC')->applyIfNotPresent('filter1','filter2');
```

Sorting
-------

[](#sorting)

Like with filtering you can declare sorting query parameters via the `OrderBy` parameter in many ways:

```
$resource->orderBy->add(''[,][,]);
$resource->orderBy->;
$resource->orderBy[''];
$resource->orderBy->([,][,]);
```

For each filter you can specify a related table field to order with the `field('')` function and a default sorting direction with `defaultOrder('')`. If you want the sorting direction to be fixed and not modifiable by the user you can use the `direction('')` method.

If you want to customize the sorting you can pass a callback as the `field` parameter; the query where the sorting will be applied will be passed as first argument and the sorting direction as second argument.

Example:

```
$resource->orderBy->email->field('email');
$resource->orderBy->name->field('username')->defaultOrder('desc');
// Forced ascending
$resource->orderBy->add('name-asc','username','asc');
// Example custom filter
$resource->orderBy->test1->field(function($query,$direction){
    $query->orderBy('email',$direction)
          ->orderBy('name',$direction)
          ->orderBy('id','asc');
});
```

### Default sorting order

[](#default-sorting-order)

If you want to specify a default sorting order you can

Order query parameter
---------------------

[](#order-query-parameter)

The filter query parameter can be set with the `$orderField` parameter of the ResourceQuery. The filter can be specified as a key value with the sorting parameter as key and the direction as a value or by using one of the two short syntax (as string, comma separated):

- `[:]`
- `[+|-]` where prepending "+" means ascending order and "-" descending order

Example:

```
page?order_by[field1]=&order_by[field2]=asc&order_by[field3]=desc

```

Or

```
page?order_by=field1,field2:asc,field3:desc

```

Or

```
page?order_by=field1,+field2,-field3

```

Javascript API
--------------

[](#javascript-api)

The package does include a Javascript counterpart to help query the back-end; the package is distributed with the composer package instead of a separate npm package as it's strictly related to the php implementation.

Include it in `resources/js/app.js`

```
import ResourceQuery from "../../vendors/plokko/resource-query/js/ResourceQuery";
// Make it available in pages
window.ResourceQuery = ResourceQuery;
//...
```

*Note: Axios is required as a dependency*

### Usage

[](#usage)

Instantiate a new ResourceQuery by specifying target URL and method (default get):

```
let rq = new ResourceQuery('/url','get');
```

The back-end should be something as follow:

```
class MyController extends Controller {
    //...
    function testPage(Request $request){
        $resource = new UserResourceQuery();
        //...add filters, etc.

        // if it's an Ajax resource return the resource directly
        if($request->ajax()){
            return $resource;
        }

        // Or else return the HTML page
        return view('mypage');
    }
    //...
}
```

You can add or modify filters, sorting and options

```
// Set filters root parameter (must be the same as the back-end)
rq.filtersRoot = 'filters';
// Set orderby parameter (must be the same as the back-end)
rq.orderField = 'order_by';

// Add a filter
rq.filters.test1 = 'a';
// or
rq.filter('test1','a');
// or
rq.addFilters({test1:'a',test2:'b'});

// Order
rq.order_by = ['field1',['field2','desc']];
// or
rq.orderBy('field1','asc');

// Clears all the filters
rq.clearFilters();
// Clears all the orderby options
rq.clearOrderBy();
//Clears all the filters and orderby options
rq.resetQuery();

// Set page (if pagination is enabled)
rq.page = 2;
// Set the page size (may be ignored by the back-end if not allowed)
rq.pageSize = 10; // 10 element per page
```

### Request cancellation and options

[](#request-cancellation-and-options)

Request cancellation is supported via a token option:

```
let rq = new ResourceQuery('/url','get');
let cancelToken = ResourceQuery.cancelToken;
rq.get({cancelToken})
    .then(r => {
        console.log('Data received',r);
    })
    .catch(e => {
        // Check if the request was user-cancelled
        if (ResourceQuery.isCancel(e)) {
            //the request was user-cancelled, no error thrown
            console.warn('user cancelled');
        } else {
            console.error('Request error:', e);
        }
    });
//...

// When you want to cancel the request
cancelcancelToken.cancel();
```

See [Axios request configuration](https://github.com/axios/axios#request-config) for other supported configuration options (some proprieties may be ignored)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance54

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity42

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 ~218 days

Recently: every ~332 days

Total

8

Last Release

306d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3899114?v=4)[plokko](/maintainers/plokko)[@plokko](https://github.com/plokko)

---

Top Contributors

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

---

Tags

ajaxeloquentfilterlaravelquerysortinglaraveleloquentqueryfilterresourcepaginate

### Embed Badge

![Health badge](/badges/plokko-resource-query/health.svg)

```
[![Health](https://phpackages.com/badges/plokko-resource-query/health.svg)](https://phpackages.com/packages/plokko-resource-query)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[mehdi-fathi/eloquent-filter

Eloquent Filter adds custom filters automatically to your Eloquent Models in Laravel.It's easy to use and fully dynamic, just with sending the Query Strings to it.

450191.6k1](/packages/mehdi-fathi-eloquent-filter)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[aldemeery/sieve

A simple, clean and elegant way to filter Eloquent models.

1396.3k](/packages/aldemeery-sieve)[omalizadeh/laravel-query-filter

A laravel package for resource filtering via request query string

163.0k](/packages/omalizadeh-laravel-query-filter)

PHPackages © 2026

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