PHPackages                             bakgul/laravel-query-helper - 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. [Search &amp; Filtering](/categories/search)
4. /
5. bakgul/laravel-query-helper

ActiveLibrary[Search &amp; Filtering](/categories/search)

bakgul/laravel-query-helper
===========================

A package to add some wrapper around filtering, groupping, sorting and maybe more to write queries faster.

v1.0.2(3y ago)115PHP

Since Feb 15Pushed 3y ago1 watchersCompare

[ Source](https://github.com/bulentAkgul/laravel-query-helper)[ Packagist](https://packagist.org/packages/bakgul/laravel-query-helper)[ RSS](/packages/bakgul-laravel-query-helper/feed)WikiDiscussions main Synced 1mo ago

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

Laravel Query Helper
====================

[](#laravel-query-helper)

This package aims to add a handy and quite flexible features to Laravel's Eloquent query builder.

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

[](#installation)

First, install package.

```
sail composer require bakgul/laravel-query-helper

```

Next, pulish config.

```
sail artisan vendor:publish --tag=query-helper

```

Usage
-----

[](#usage)

### Filtering

[](#filtering)

First, you need to add `IsFilterable` trait and an array of filters to each model where you want to apply filters. That array can have two keys:

- Self: the list of filters that will be applied directly to that model.
- With: an associative array of related models that can be used to filter the main model. The keys in this array must be the same as the method names of the relations.

Let's say we have the following models and relations.

```
class User extends ...
{
    use IsFilterable, ...;

    public static $filters = [
        'self' => [
            \Bakgul\LaravelQueryHelper\Filters\Name::class,
            \Bakgul\LaravelQueryHelper\Filters\Email::class,
        ],
        'with' => [
            'roles' => Role::class,
        ]
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}
```

```
class Role extends Model
{
    use IsFilterable;

    private static array $filters = [
        'self' => [
            \Bakgul\LaravelQueryHelper\Filters\Name::class,
        ],
        'with' => [
            'users' => User::class,
            'abilities' => Ability::class,
        ],
    ];

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function abilities()
    {
        return $this->belongsToMany(Ability::class);
    }
}
```

```
class Ability extends Model
{
    use IsFilterable;

    private static array $filters = [
        'self' => [
            \Bakgul\LaravelQueryHelper\Filters\Name::class
        ],
        'with' => [
            'roles' => Role::class,
        ]
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}
```

```
$users = User::filter($request->filters)->get();
```

When you call `filter` method, it will generate a filtering array throughout the `filters` array on models starting from `User` recursively.

To prevent infinite loop in recursion, we stop each branch when they go back to main class after adding main class to the tree. That means You can filter by the following logic:

- Users that have cetain roles that belongs to some users.
-

This example might not be seen very usefull, but it explains the capability.

Since it's an expensive operation to construct the filtering array, we will cache it when it's created first time.

`$request->filters` should be in a structure like the example down below. The important things here:

- `self` filters will be passed directly.
- `with` filters will be collected under `with` key.

```
[
    // *** will be replaced by % by the Text filter.
    // ***x means the string that ends with 'x'
    // x*** means the string that start with 'x',
    // ***x*** means the string that contains 'x',
    // x means the string that is 'x'
    'name' => ['***x***', '***y'],
    'with' => [
        'roles' => [
            'name' => ['editor***'],
            'with' => [
                'abilities' => [
                    'name' => ['delete']
                ]
            ]
        ]
    ]
]
```

The example up above will filter the users based on the following list:

- its name contains 'x' or ends with 'y'
- the name of one of its roles starts with 'editor'
- the role can delete something.

#### *Polymorphic Relationship Filter*

[](#polymorphic-relationship-filter)

Unlike other relationships, polymoprphic ones should be listed under the `self` key of `$filters` array.

```
class Post extends Model
{
    use IsFilterable;

    private static array $filters = [
        'self' => [
            \Bakgul\LaravelQueryHelper\Filters\MorphMany::class
        ],
        'with' => [
            'user' => User::class,
        ],
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->morphToMany(Comment::class, 'commentable');
    }
}
```

The filter in request should be like this:

```
[
    'morph_many' => [
        // method name: 'to' if the relation method is 'morphToMany'
        //              'by' if the relation method is 'morphedByMany'
        'to',
        // relationsip name
        'comments',
        // prefix:
        //     if 'to' then this will be 'comment_id'
        //     if 'by' then this will be 'commentable_id' and 'commentable_type'
        'comment',
        // the N number of ids that will be cheched in the column up above
        2, 3, 5
    ]
]
```

### Groupping

[](#groupping)

Groupping operates on PHP level. If you want to group your data in the database level, you can't use this part. Otherwise, this is how to use it:

- Add `IsGrouppable` trait to the model that you want to group.
- If you want to group a model with some columns all the time, add `protected static $groupKeys = ['name', 'year']` property to the model.
- Then use it like so:

```
/**
 * users table has these columns:
 *     first_name,
 *     last_name,
 *     email,
 *     ... some irrelevant columns
 *     created_at
 */

$users = User::group(['first_name']);
```

`group` method can be found in `IsGrouppable` trait as `scopeGroup` and it accepts the following arguments:

- **keys**: the list of group keys
- **take**: the number of items that will be in each group. Default is zero and means 'all'
- **isLast**: make it true when you want to get latest records. Default is false.
- **select**: the array of columns that will be selected. Default is \['\*'\] means 'all'
- **column**: the name of the column when you needed. I use it for the time modifiers such as year and month. Its default value is 'created\_at'

But what if you want to group users with a column that doesn't exist. You can do that thanks to modifiers that are shipped in the package and can be be found on `src/Modifiers`.

The modifiers will change the sql query to add new field on the fly. For example:

```
$users = User::group(
    keys: ['year', 'email_provider'],
    take: 5,
    isLast: true,
    select: ['first_name', 'last_name', 'email']
    column: 'updated_at'
);
```

The method up above will add `year` and `email_provider` fields to the each user. `year` will be extracted from `updated_at` while `email_provider` from `email`. Each user will contain selected 3 columns and these 2.

### Modifiying

[](#modifiying)

This is used by groupping functionality, and it's already explained, but just as a remainder, you can use it out of grouping too.

- Add `IsModifyable` trait to model.
- call `modify` method as a part of query builder.

```
$users = User::modify(
    keys: ['year', 'month'],
    select: ['name', 'email'],
    column: 'updated_at'
)->get();
```

### Sorting

[](#sorting)

It's a quite simple method that allowes you to pass all sorting columns in one method.

```
User::sort(['name'], ['email', 'desc']);
```

Extending Functionalities
-------------------------

[](#extending-functionalities)

### Filtering

[](#filtering-1)

In order to extend available filters, all you need to do is to create your own filter classes and use them in models. Let's say you have a table that contains `city` and need to apply a filter to it.

First create a class. The class name must be the pascal case version of the key that you will pass in request.

```
namespace App\Filters;

class City extends Text
{
    public $column = 'city';
}
```

Or you can create your own filtering logic instead of using `Text` filter.

```
namespace App\Filters;

class City extends Filter
{
    protected function filter(Builder $query, mixed $filter): Builder
    {
        // if you want to accept multiple values, call filters method
        return $this->filters($query, $filter, $this->callback());

        // otherwise...
        return $query->where('city', $filter);
    }

    protected function callback(): callable
    {
        return fn ($query, $filter) => $query->where('city', $filter);
    }
}
```

After you create your new filter class, add it to model which can use it.

```
class Address extends Model
{
    private static array $filters = [
        'self' => [
            \Bakgul\LaravelQueryHelper\Filters\Name::class,
            \App\Filters\City::class,
        ],
        'with' => [
            'user' => User::class,
            'country' => Country::class,
        ],
    ];
}
```

Now, you can filter addresses based on city, or users who is in that city/cities.

```
Adress::filter(['city' => ['ankara', 'london']])->get();

User::filter(['with' => ['city' => ['ankara', 'london']]])->get();
```

### Groupping

[](#groupping-1)

If you want to use one of your current columns as they are, you don't need to take any action. Simply pass the column name in the array of group keys.

But let's say you have `domain` column where you store the web sites' adresses and you want to group them beased on top-level domain (.com, .net, etc.)

First you need a modifier to extract that part and store it in a new field in query.

```
namespace App\Modifiers;

class TopLevelDomain extends Modify
{
    public function modifyQuery(Builder $query, array $keys, string $column): Builder
    {
        $raw = $this->rawQuery();

        return $query->when(
            in_array('top_level_domain', $keys),
            fn ($q) => $q->addSelect($raw)
        );
    }

    private function rawQuery(): Expression
    {
        return DB::raw("REPLACE(domain, SUBSTRING_INDEX(domain, '.', 1) , '') as top_level_domain");
    }
}
```

Then you need to add it to `modifiers` array in `config/query-helper.php`

```
    'modifiers' => [
        // default ones,
        \App\Modifiers\TopLevelDomain::class,
    ]
```

Now you can use it like so:

```
$customers = Customer::group(['top_level_domain']);
```

License
-------

[](#license)

This is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

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

Total

3

Last Release

1181d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dc3c26b9029d2705ffcd2baebee543db52c24b1fb5cb29c5557436de853d42c1?d=identicon)[bulentAkgul](/maintainers/bulentAkgul)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/bakgul-laravel-query-helper/health.svg)

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

###  Alternatives

[ruflin/elastica

Elasticsearch Client

2.3k50.4M203](/packages/ruflin-elastica)[opensearch-project/opensearch-php

PHP Client for OpenSearch

15224.3M65](/packages/opensearch-project-opensearch-php)[mailerlite/laravel-elasticsearch

An easy way to use the official PHP ElasticSearch client in your Laravel applications.

934529.3k2](/packages/mailerlite-laravel-elasticsearch)[massive/search-bundle

Massive Search Bundle

721.4M13](/packages/massive-search-bundle)[shyim/opensearch-php-dsl

OpenSearch/Elasticsearch DSL library

175.9M9](/packages/shyim-opensearch-php-dsl)[outl1ne/nova-multiselect-filter

Multiselect filter for Laravel Nova.

45802.7k3](/packages/outl1ne-nova-multiselect-filter)

PHPackages © 2026

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