PHPackages                             jaikumar0101/laravel-base-filter - 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. jaikumar0101/laravel-base-filter

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

jaikumar0101/laravel-base-filter
================================

A powerful and flexible Laravel package for building and applying query filters with ease

v1.0.1(2mo ago)16MITPHPPHP ^8.1CI passing

Since Feb 10Pushed 2mo agoCompare

[ Source](https://github.com/Jaikumar0101/laravel-base-filter)[ Packagist](https://packagist.org/packages/jaikumar0101/laravel-base-filter)[ RSS](/packages/jaikumar0101-laravel-base-filter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

Laravel Base Filter
===================

[](#laravel-base-filter)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fdd7ef5241dbd1199fc915fbe5124e2613ccb84eecccef768b152d67dacbdf08/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a61696b756d6172303130312f6c61726176656c2d626173652d66696c7465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-base-filter)[![Total Downloads](https://camo.githubusercontent.com/49c40edb5a384303f41000af7fdeb7a545b96515b957b0040c968246f520bea9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a61696b756d6172303130312f6c61726176656c2d626173652d66696c7465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-base-filter)[![License](https://camo.githubusercontent.com/ecd0bea1ba3e3b2d9cbf9652ac7e0a41e93690c92081ec6b79f35eddf72c58b8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a61696b756d6172303130312f6c61726176656c2d626173652d66696c7465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jaikumar0101/laravel-base-filter)

A powerful and flexible Laravel package for building and applying query filters with ease. This package provides a fluent interface for constructing complex database queries with filters, search, sorting, relations, and custom callbacks.

Features
--------

[](#features)

- 🔍 **Flexible Filtering**: Build complex where conditions, whereIn, and relation filters
- 🎯 **Advanced Relationship Filters**: Filter with `whereHas` and `whereDoesntHave` using custom callbacks
- ⚡ **Raw SQL Support**: Execute complex SQL expressions with `whereRaw` for advanced queries
- 🔧 **Callback Conditions**: Use `whereCallback` for complete control over complex nested queries
- 🔎 **Smart Search**: Search across multiple columns including relationships
- 🔄 **Sorting**: Easy sorting with customizable defaults
- 🗑️ **Soft Delete Support**: Handle trashed records with ease
- 🎨 **Custom Filters**: Add custom filter logic with callables
- 🎭 **Fluent API**: Chainable methods for clean, readable code
- ⚙️ **Configurable**: Customize defaults via config file
- 🧪 **Well Tested**: Comprehensive test suite included
- 🎭 **Facade Support**: Use facades or dependency injection

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x

What's New in v1.1 🎉
--------------------

[](#whats-new-in-v11-)

### Advanced Relationship Filters

[](#advanced-relationship-filters)

- **`setWhereHas()`** - Filter records based on relationship existence with custom callback conditions
- **`setWhereDoesntHave()`** - Inverse filtering - exclude records with specific relationships

### Raw SQL &amp; Complex Conditions

[](#raw-sql--complex-conditions)

- **`setWhereRaw()`** - Execute complex SQL expressions for advanced filtering needs
- **`setWhereCallback()`** - Build complex nested where clauses with complete query builder control

### Enhanced Power &amp; Flexibility

[](#enhanced-power--flexibility)

These new features enable you to build more sophisticated filters for real-world scenarios like:

- Multi-level relationship filtering
- Complex date calculations and comparisons
- Custom business logic with raw SQL
- Dynamic conditional filtering based on user permissions

See the [complete documentation](#advanced-relationship-filters-new) and [examples](EXAMPLES.md) for usage details.

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

[](#installation)

Install the package via Composer:

```
composer require jaikumar0101/laravel-base-filter
```

Publish the configuration file (optional):

```
php artisan vendor:publish --provider="Jaikumar0101\LaravelBaseFilter\QueryFilterServiceProvider"
```

Basic Usage
-----------

[](#basic-usage)

### Creating Filters

[](#creating-filters)

```
use Jaikumar0101\LaravelBaseFilter\Facades\QueryFilter;

// Using the facade
$filters = QueryFilter::make()
    ->setWhere('status', '=', 'active')
    ->setSearch($request->get('search'), ['name', 'email'])
    ->setSort('created_at', 'desc')
    ->toArray();

// Or using the helper function
$filters = query_filter()
    ->setWhere('company_id', '=', auth()->user()->company_id)
    ->setWhereIn('role', ['admin', 'manager'])
    ->setSearch($request->search, ['code', 'reference'])
    ->toArray();
```

### Applying Filters

[](#applying-filters)

```
use Jaikumar0101\LaravelBaseFilter\Facades\FilterApplier;
use App\Models\User;

// Apply filters to a query
$query = User::query();
$filteredQuery = FilterApplier::on($query, $filters)->applyAll();
$users = $filteredQuery->paginate(15);

// Or use the helper
$users = filter_applier(User::query(), $filters)
    ->applyAll()
    ->paginate(15);
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom Filters with Callables

[](#custom-filters-with-callables)

Add custom filter logic using callbacks:

```
$filters = QueryFilter::make()
    ->setWhere('status', '=', 'active')
    ->setCustom('price_range', function ($query, $value) {
        if (isset($value['min'])) {
            $query->where('price', '>=', $value['min']);
        }
        if (isset($value['max'])) {
            $query->where('price', '', 100);
    })
    ->toArray();
```

### Advanced Relationship Filters (NEW)

[](#advanced-relationship-filters-new)

#### WhereHas with Custom Callbacks

[](#wherehas-with-custom-callbacks)

```
// Filter users who have published posts with over 100 views
$filters = QueryFilter::make()
    ->setWhereHas('posts', function ($query) {
        $query->where('published', true)
              ->where('views', '>', 100);
    })
    ->toArray();

// Multiple whereHas conditions
$filters = QueryFilter::make()
    ->setWhereHas('company', fn($q) => $q->where('status', 'active'))
    ->setWhereHas('roles', fn($q) => $q->whereIn('name', ['admin', 'manager']))
    ->toArray();
```

#### WhereDoesntHave (Inverse Filtering)

[](#wheredoesnthave-inverse-filtering)

```
// Users without any posts
$filters = QueryFilter::make()
    ->setWhereDoesntHave('posts')
    ->toArray();

// Users without published posts
$filters = QueryFilter::make()
    ->setWhereDoesntHave('posts', fn($q) => $q->where('published', true))
    ->toArray();

// Invoices without successful payments
$filters = QueryFilter::make()
    ->setWhereDoesntHave('payments', fn($q) => $q->where('status', 'success'))
    ->toArray();
```

### Raw SQL Conditions (NEW)

[](#raw-sql-conditions-new)

```
// Year-based filtering
$filters = QueryFilter::make()
    ->setWhereRaw('YEAR(created_at) = ?', [2024])
    ->toArray();

// Complex calculations
$filters = QueryFilter::make()
    ->setWhereRaw('(quantity * unit_price) - discount > ?', [1000])
    ->setWhereRaw('DATEDIFF(due_date, invoice_date) > ?', [30])
    ->toArray();

// Profit margin analysis
$filters = QueryFilter::make()
    ->setWhereRaw('((selling_price - cost_price) / cost_price * 100) >= ?', [20])
    ->toArray();
```

### Callback-Based Where Conditions (NEW)

[](#callback-based-where-conditions-new)

```
// Complex nested where conditions
$filters = QueryFilter::make()
    ->setWhereCallback(function ($query) {
        $query->where(function ($q) {
            $q->where('status', 'active')
              ->orWhere('status', 'pending');
        })->where('amount', '>', 100);
    })
    ->toArray();

// Dynamic complex conditions
$filters = QueryFilter::make()
    ->setWhere('company_id', '=', $companyId)
    ->setWhereCallback(function ($query) use ($isUrgent) {
        if ($isUrgent) {
            $query->where(function ($q) {
                $q->where('priority', 'high')
                  ->orWhere('due_date', '', 500);
                }
            })

            // Exclude orders with cancelled payments
            ->setWhereDoesntHave('payments', fn($q) => $q->where('status', 'cancelled'))

            // Complex date calculations
            ->setWhereRaw('DATEDIFF(delivery_date, order_date)  ?', [$request->min_value ?? 0])

            // Complex nested conditions
            ->setWhereCallback(function ($query) use ($request) {
                if ($request->has('urgent_filter')) {
                    $query->where(function ($q) {
                        $q->where('priority', 'urgent')
                          ->orWhere('delivery_date', 'only(['whereHas', 'search'])
    ->getQuery();
```

#### `except(array $types): self`

[](#exceptarray-types-self)

Apply all filters except specified types. Uses the same type names as `only()`.

**Example:**

```
// Apply all filters except sorting
$query = FilterApplier::on(User::query(), $filters)
    ->except(['sort'])
    ->getQuery();
```

Configuration
-------------

[](#configuration)

The published config file (`config/query-filter.php`) allows you to customize:

```
return [
    'defaults' => [
        'sort_by' => 'id',
        'sort_order' => 'desc',
        'search_operator' => 'like',
    ],
    'search' => [
        'enable_full_name' => true,
        'case_sensitive' => false,
    ],
];
```

Testing
-------

[](#testing)

Run the tests:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

Support
-------

[](#support)

If you discover any issues or have questions, please open an issue on [GitHub](https://github.com/Jaikumar0101/laravel-base-filter/issues).

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request. See [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

License
-------

[](#license)

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

Credits
-------

[](#credits)

- [Jai Kumar](https://github.com/Jaikumar0101)
- [All Contributors](https://github.com/Jaikumar0101/laravel-base-filter/contributors)

Links
-----

[](#links)

- [GitHub Repository](https://github.com/Jaikumar0101/laravel-base-filter)
- [Packagist](https://packagist.org/packages/jaikumar0101/laravel-base-filter)
- [Issues](https://github.com/Jaikumar0101/laravel-base-filter/issues)

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance83

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

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

2

Last Release

88d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/752c03fcc0f87f8d495425a90f03cdf640082509175be2a5a09d5a27f6533e1b?d=identicon)[Jaikumar0101](/maintainers/Jaikumar0101)

---

Top Contributors

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

---

Tags

searchlaraveleloquentqueryfiltersort

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jaikumar0101-laravel-base-filter/health.svg)

```
[![Health](https://phpackages.com/badges/jaikumar0101-laravel-base-filter/health.svg)](https://phpackages.com/packages/jaikumar0101-laravel-base-filter)
```

###  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)[mohammad-fouladgar/eloquent-builder

527189.5k](/packages/mohammad-fouladgar-eloquent-builder)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[jedrzej/pimpable

Laravel 4/5/6 package that allows to dynamically filter, sort and eager load relations for your models using request parameters

105179.0k1](/packages/jedrzej-pimpable)[aldemeery/sieve

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

1396.3k](/packages/aldemeery-sieve)

PHPackages © 2026

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