PHPackages                             makaveli/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. [Framework](/categories/framework)
4. /
5. makaveli/laravel-query-builder

ActiveLibrary[Framework](/categories/framework)

makaveli/laravel-query-builder
==============================

Query Builder for Laravel

1.1.5(1mo ago)0332MITPHPPHP ^8.2

Since Apr 20Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Ma1kaveli/laravel-query-builder)[ Packagist](https://packagist.org/packages/makaveli/laravel-query-builder)[ RSS](/packages/makaveli-laravel-query-builder/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (10)Versions (23)Used By (2)

makaveli/laravel-query-builder
==============================

[](#makavelilaravel-query-builder)

[![Packagist Version](https://camo.githubusercontent.com/810b26dbf1bfdae268990abcedf5ec55cef25f2f96f73df401844436de496efe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616b6176656c692f6c61726176656c2d71756572792d6275696c6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-query-builder)[![Packagist Downloads](https://camo.githubusercontent.com/2ca4da3823c8df88086759e15ad5e0736aed72d0275372e3c71217245c11e1c2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616b6176656c692f6c61726176656c2d71756572792d6275696c6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-query-builder)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

🌍 Languages
-----------

[](#-languages)

- 🇺🇸 English (default)
- 🇷🇺 [Русская версия](docs/ru/README.md)

Table of Contents
-----------------

[](#table-of-contents)

1. [Introduction](#introduction)
2. [Installation](#installation)
3. [Configuration](#configuration)
4. [Core Components](#core-components)
    - [BaseQueryBuilder](#basequerybuilder)
    - [Filterable Trait](#filterable-trait)
    - [CheckTypes](#checktypes)
    - [PaginatedCollection](#paginatedcollection)
    - [DTOs for Complex Parameters](#dtos-for-complex-parameters)
    - [Filters](#filters)
5. [Quick Start](#quick-start)
6. [Integration with BaseRepository](#integration-with-baserepository)
7. [Recommendations](#recommendations)
8. [Useful Links](#useful-links)

Introduction
------------

[](#introduction)

**makaveli/laravel-query-builder** is a powerful and convenient query builder for Laravel Eloquent. It allows you to extract all filtering, sorting, and pagination logic into separate classes that extend `BaseQueryBuilder`. This approach keeps controllers and repositories clean while making the filtering code readable, extensible, and safe.

Key goals of the library:

- **Readability** – each `$this->apply...()` method describes one clear condition.
- **Security** – parameters are only taken from the passed `$params` array.
- **Extensibility** – adding a new filter is easy by implementing `FilterInterface`.
- **Reusability** – a single filter class can be used in different contexts (admin panel, API, reports).
- **Type Safety** – all methods are strictly typed, and built‑in type checks (`CheckTypes`) prevent errors.

The library integrates closely with [makaveli/laravel-core](https://github.com/Ma1kaveli/laravel-core). It requires PHP 8.2+ and Laravel 10+.

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

[](#installation)

1. Install the library via Composer:

    ```
    composer require makaveli/laravel-query-builder
    ```
2. (Optional) Publish the configuration file if you want to change the default settings:

    ```
    php artisan vendor:publish --tag=query-builder-config
    ```

    This will create the file `config/query-builder.php` in your project.

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

[](#configuration)

The file `config/query-builder.php` contains the following settings:

```
return [
    // Date and time formats supported by CheckTypes
    'check-types' => [
        'date-formats' => ['Y-m-d', 'd.m.Y', 'm/d/Y', 'd F Y', 'Y-m-d H:i:s'],
        'time-formats' => ['H:i', 'H:i:s', 'H:i:s.u']
    ],

    // Pagination key mapping for PaginatedCollection
    'pagination_map' => [
        'current_page' => 'current_page',
        'first_page_url' => 'first_page_url',
        'from' => 'from',
        'last_page' => 'last_page',
        'last_page_url' => 'last_page_url',
        'links' => 'links',
        'next_page_url' => 'next_page_url',
        'path' => 'path',
        'per_page' => 'per_page',
        'prev_page_url' => 'prev_page_url',
        'to' => 'to',
        'total' => 'total',
    ],
];
```

You can change the supported date/time formats and the pagination response structure according to your API requirements.

Core Components
---------------

[](#core-components)

### BaseQueryBuilder

[](#basequerybuilder)

An abstract base class from which all concrete filter classes inherit. It holds an instance of `$query` (Eloquent Builder) and the array `$params` (request parameters). It contains many protected methods for applying filters (e.g., `applyInteger()`, `applyLike()`, `applyWhereHasWhere()`, `applyDateRange()`, etc.).

A detailed description of all methods with examples is provided in a separate document: **[base-query-builder.md](docs/en/base-query-builder.md)**.

### Filterable Trait

[](#filterable-trait)

The trait is added to a model and allows calling filters via the static `filter()` method:

```
trait Filterable
{
    public static function filter(array $params): mixed
    {
        $query = static::query();
        $filterClass = static::getFilterClass();

        if (class_exists($filterClass)) {
            return new $filterClass($query, $params);
        }

        return $query;
    }

    abstract public static function getFilterClass(): string;
}
```

The model must implement `getFilterClass()`, returning the fully qualified class name of the filter class.

### CheckTypes

[](#checktypes)

The helper class `QueryBuilder\Helpers\CheckTypes` contains static methods for checking data types. It is used internally by filters to ensure that a passed value matches the expected type (integer, float, string, date, time, array, etc.). This improves security and prevents query errors.

### PaginatedCollection

[](#paginatedcollection)

The class `QueryBuilder\Resources\PaginatedCollection` extends the standard `ResourceCollection` and makes it easy to adapt the paginated response structure to frontend requirements. It uses the configuration key `pagination_map` to rename response fields.

Usage example:

```
use QueryBuilder\Resources\PaginatedCollection;

return new PaginatedCollection(
    $paginator,
    ArticleResource::collection($paginator, ['author'])
);
```

The result will contain the keys defined in `pagination_map`, and the actual data will be inside the `data` key.

### DTOs for Complex Parameters

[](#dtos-for-complex-parameters)

The package provides several DTO classes for passing complex parameters to filters:

- `AvailableSort` and `AvailableSorts` – for describing allowed sorts on fields of related tables.
- `DeepWhereHasWhereParam` and `DeepWhereHasWhereParams` – for building nested `whereHas` conditions.

These DTOs are used in the methods `sortByRelationField()` and `applyDeepWhereHasWhere()`.

### Filters

[](#filters)

All filters reside in the namespace `QueryBuilder\Filters` and are organized into categories:

Category\# of FiltersExample Methods / Features**Datetime**~20`applyToday()`, `applyLastWeek()`, `applyDateRange()`, `applyCurrentHour()`, `applyTimeStartEnd()`, `applyLastMonth()`**Numeric**~15`applyNumericRange()`, `applyMultipleOf()`, `applyEvenNumeric()`, `applyArrayInteger()`, `applyNumericNot()`, `applyNumericNotIn()`**String**~10`applyLike()`, `applyLikeStart()`, `applyLikeEnd()`, `applyRegex()`, `applyFullTextSearch()`**Logic**~8`applyNull()`, `applyTrue()`, `applyFalse()`, `applyNotNull()`, `applyEmpty()`**Relation**~10`applyDeepWhereHasWhere()`, `applyCrossUponCrossWhereHasWhere()`, `applyWhereHasLikeArray()`**Combine**~8`applyWhereHasWhere()`, `applyWhereHasLike()`, `applyWhereHasNull()`**System**~12`applyLimit()`, `applySelect()`, `applyDistinct()`, `with()`, `withCount()`, `inRandomOrder()`, `applyWhereNot()`, `applyWhereNotIn()`**Geo**2`applyGeoRadius()`, `applyGeoBoundingBox()`**Special**4`applyIpAddress()`, `applyRating()`, `applyStock()`, `applyDomain()`**Custom**2`applyArchived()`, `applyWhereNotMe()`A complete list of all filters with detailed descriptions, parameters, and examples can be found in **[base-query-builder.md](docs/en/base-query-builder.md)**.

Quick Start
-----------

[](#quick-start)

### 1. Create a filter class

[](#1-create-a-filter-class)

```
