PHPackages                             phatnt99/advanced-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. phatnt99/advanced-query

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

phatnt99/advanced-query
=======================

Powerful query for filter, sort and custom Eloquent query.

v1.0(5y ago)2154MITPHPPHP ^7.2

Since Nov 15Pushed 5y ago2 watchersCompare

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

READMEChangelog (1)DependenciesVersions (2)Used By (0)

advanced-query
==============

[](#advanced-query)

A package provides an advanced query for Eloquent Laravel.

Requirements
------------

[](#requirements)

This package require:

- PHP 7.2+

Installation
============

[](#installation)

Install the package through composer:

```
composer require phatnt99/advanced-query
```

Laravel
-------

[](#laravel)

> The package supports auto-discovery, so if you use Laravel 5.5 or later you may skip this step.

Append the following line to the `providers` key in `config/app.php` to add the service provider

```
Phatnt99\AdvancedQuery\QueryServiceProvider::class
```

Usage
=====

[](#usage)

This package support 3 key features: **filter**, **sort** and **custom query**.

To get started, run the bellow Artisan command:

```
php artisan make:query UserQuery --fs

```

**Note**: you need to define your model before running this command, the word User in that query name will use to find existed model. If no model corresponds to the name provided, the error will show and cause unexpected behavior (but you can change the correct class model after that).

The `--fs` option will create class Filter and Sort, if you just custom your query then remove this.

The above command will create 3 files in `App\Queries`:

```
-Queries
|
--Filters
| |
| --UserFilter.php
| |
--Sorts
| |
| --UserSort.php
|
--UserQuery.php

```

Let deep to detail

Filter
------

[](#filter)

### Default filter

[](#default-filter)

The package ship with 3 attributes to save your time. Instead of doing this:

```
return $query->where('name','LIKE', '%'.$name.'%');
...
return $query->where('email', '=', $email);
...
return $query->whereDate('created_at', '=', date('Y-m-d'));
```

You can use this:

```
protected $filterPartial = [
	'name'
];

protected $filterExact = [
	'email'
];

protected $filterDate = [
	'created_at'
];
```

It reduces time to write duplicate code and make the class where you perform some filter function more readable :)

### Filter date in range

[](#filter-date-in-range)

A small tip with date filter, if you want to filter date in range (from...to). Try that:

```
    protected $filterDate = [
        'from.created_at',
        'to.created_at'
    ];
```

### Custom filter

[](#custom-filter)

Sometimes your filter work with complicated logic (like filtering on a relationship attribute), the filter class help you custom your own function to perform complex filter

```
protected function project($projectId)
{
	return $this->query->whereHas('projects', function ($query) use ($projectId) {
            $query->where('project_id', '=', $projectId);
        });
}
```

Then use the function name like attribute name in query string.

### Using in query string

[](#using-in-query-string)

You can pass the attribute along with value want to be filter by **filters** key:

```
GET /users?filters[name]=John&filters[created_at]=2020-02-02

```

Sort
----

[](#sort)

### Default sort

[](#default-sort)

The concrete Sort class has attribute defaultSorts which let you define sortable attributes.

```
protected $defaultSorts = [
        'full_name',
        'nick_name',
        'dob',
        'email',
        'phone_number',
];
```

For attribute has constant direction, use enum SortDirection for its value

```
protected $defaultSorts = [
		...
        'dob' => SortDirection::DESCENDING,
];
```

**Note**: If the attribute has both a default direction (like above) and a direction in the query string, it will treat direction in the query string as a higher priority.

### Using in query string

[](#using-in-query-string-1)

I use **sort** key with prefix - to perform descending sort (none is ascending):

```
GET /users?sort=id,-dob

```

Query
-----

[](#query)

This is the class that binds the main functions of the package. You must define some important attributes that point to dependendcy classes

```
/**
* Your model class
* @var string
*/
protected $model = User::class;

/**
* Your filter class
* @var string
*/
protected $filter = UserFilter::class;

/**
* Your sort class
* @var string
*/
protected $sort = UserSort::class;
```

If you use the full command (with --fs option and correct model) it will automatically bind these value for you (or just model class if not using --fs option).

Just specify the dependent classes (with the full handler in each dependency) and you can use the main power of the package.

```
// UserController

public function index(UserQuery $query)
{
   return response()->json(
			$query->filter()
				->sort()
				->paginate());
}
```

### Allowed attributes

[](#allowed-attributes)

In case you want to restrict only some attributes allowed to be filtered or sorted, pass these attribute to **allows** argument (the 2nd paramater)

```
   return response()->json(
			$query->filter(null, ['id', 'name'])
				->sort(null, ['created_at'])
				->paginate());
```

### Eloquent Query &amp; Advanced Query

[](#eloquent-query--advanced-query)

You can use Eloquent methods (where, whereHas,...) directly with an instance of Query class but it will lost the chain (chaining methods). A better way, define your own method which use these Eloquent method and then return the Query instance

```
// UserQuery

/**
* Advanced Query
*/
public function verifiedUser() {
	$this->query->whereNotNull('email_verify_at');
	return $this;
}
```

### Paginate

[](#paginate)

I use default paginate of Eloquent model which allow you pass the index of expected page into `paginate()` (default is 1).

Other usage
-----------

[](#other-usage)

You can use each feature independently.

### Filter &amp; Sort independent

[](#filter--sort-independent)

You must set the query attribute to use these independently. Example (the same method for sort):

```
$filter = new \App\Queries\Filters\UserFilter();
$filter->setQuery(User::query());
```

Instead of passing attributes (with value) into the query string, you can pass it into `setAllowAttrs` method:

```
$filter = new \App\Queries\Filters\UserFilter();
$filter->setQuery(User::query())
	   ->setAllowAttrs(['name' => 'John'])
	   ->getCollection();
```

Then you can easily get collection result with `getCollection` method.

By the way, the package provides 2 separate commands for filter and sort:

```
php artisan make:filter UserFilter
php artisan make:sort UserSort

```

**Happy Coding!**

Contributing
============

[](#contributing)

If you find some issue or want to make it better with your code, feel free to make PR or Issue :)

License
=======

[](#license)

The MIT License (MIT)

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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

Unknown

Total

1

Last Release

2010d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/43845547?v=4)[Phat Nguyen](/maintainers/phatnt99)[@phatnt99](https://github.com/phatnt99)

---

Top Contributors

[![phatng99](https://avatars.githubusercontent.com/u/205390756?v=4)](https://github.com/phatng99 "phatng99 (12 commits)")[![phatnt99](https://avatars.githubusercontent.com/u/43845547?v=4)](https://github.com/phatnt99 "phatnt99 (8 commits)")

### Embed Badge

![Health badge](/badges/phatnt99-advanced-query/health.svg)

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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