PHPackages                             alexmg86/laravel-sub-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. [Caching](/categories/caching)
4. /
5. alexmg86/laravel-sub-query

ActiveLibrary[Caching](/categories/caching)

alexmg86/laravel-sub-query
==========================

Laravel subquery

v1.9.9(5y ago)7538.4k↓26.3%5[1 issues](https://github.com/Alexmg86/laravel-sub-query/issues)MITPHPPHP &gt;=5.6.4

Since Apr 23Pushed 5y ago3 watchersCompare

[ Source](https://github.com/Alexmg86/laravel-sub-query)[ Packagist](https://packagist.org/packages/alexmg86/laravel-sub-query)[ Docs](https://github.com/alexmg86/laravelsubquery)[ RSS](/packages/alexmg86-laravel-sub-query/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (25)Used By (0)

[![Social Card of Laravel Sub Query](https://github.com/Alexmg86/laravel-sub-query/raw/master/art/banner.jpg)](https://github.com/Alexmg86/laravel-sub-query/blob/master/art/banner.jpg)

Laravel Sub Query
=================

[](#laravel-sub-query)

[![PHP Composer](https://github.com/Alexmg86/laravel-sub-query/workflows/PHP%20Composer/badge.svg)](https://github.com/Alexmg86/laravel-sub-query/workflows/PHP%20Composer/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/0711669700dfba31904549000340daaebff87632df4fdc4d177ba4e6a4cdaf07/68747470733a2f2f706f7365722e707567782e6f72672f616c65786d6738362f6c61726176656c2d7375622d71756572792f646f776e6c6f616473)](https://packagist.org/packages/alexmg86/laravel-sub-query)[![Latest Stable Version](https://camo.githubusercontent.com/b60cb0bf03855534386fed4322b48c62f94d1604855fc93d5b6057782b6fd3e8/68747470733a2f2f706f7365722e707567782e6f72672f616c65786d6738362f6c61726176656c2d7375622d71756572792f762f737461626c65)](https://packagist.org/packages/alexmg86/laravel-sub-query)[![License](https://camo.githubusercontent.com/0a61f0b9fc83815d3b03380d5bfb97120208a51a6573e3bf94c48b4d7e9fb907/68747470733a2f2f706f7365722e707567782e6f72672f616c65786d6738362f6c61726176656c2d7375622d71756572792f6c6963656e7365)](https://packagist.org/packages/alexmg86/laravel-sub-query)

Why is this package needed?
---------------------------

[](#why-is-this-package-needed)

With standard use of Laravel, if you want the sum or find the maximum column value in the related model, you will have two database queries. What if you need to get a list of one hundred records? With this methods, it all turns into one query to the database and there is no need to load extra data.

I've also added methods for sorting by related model, or when you only need to get one latest or oldest related model for each model without multiple queries. And there is a lot more to speed up your development and code readability.

I often use this in my work and I hope it will be useful to you!

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Say thank you
-------------

[](#say-thank-you)

If you liked this package, please give me a star.

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

[](#installation)

Install via composer

```
composer require alexmg86/laravel-sub-query
```

Use LaravelSubQueryTrait trait in your model.

```
use Alexmg86\LaravelSubQuery\Traits\LaravelSubQueryTrait;
use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    use LaravelSubQueryTrait;
```

Usage
-----

[](#usage)

If you want to get results from a relationship without actually loading them and by one request to the database you may use the these methods, which will place a new columns on your resulting models. For example:

```
$invoices = Invoice::withSum('items:price')
    ->withMin('items:price')
    ->withMax('items:price')
    ->withAvg('items:price')
    ->get();

echo $invoices[0]->items_price_sum;
echo $invoices[0]->items_price_min;
echo $invoices[0]->items_price_max;
echo $invoices[0]->items_price_avg;
```

The resulting value can be casting through the third parameter. Some types for example: date, datetime, time, char, signed, unsigned, binary.

```
$invoices = Invoice::withSum('items:price:signed')->get();
```

### The following methods apply to all methods!!!

[](#the-following-methods-apply-to-all-methods)

You may add the sum for multiple relations as well as add constraints to the queries:

```
use Illuminate\Database\Eloquent\Builder;

$invoices = Invoice::withSum(['items:price', 'goods:price,price2' => function (Builder $query) {
    $query->where('price','>',6);
}])->get();

echo $invoices[0]->items_price_sum;
echo $invoices[0]->goods_price_sum;
echo $invoices[0]->goods_price2_sum;
```

You may also alias the relationship sum result, allowing multiple sums on the same relationship:

```
use Illuminate\Database\Eloquent\Builder;

$invoices = Invoice::withSum(['items:price', 'goods:price as sum_goods_price' => function (Builder $query) {
    $query->where('price','!=',1);
}])->get();

echo $invoices[0]->items_price_sum;
echo $invoices[0]->sum_goods_price;
```

If you're combining `withSum` with a `select` statement, ensure that you call `withSum` after the `select` method:

```
$invoices = Invoice::select(['id'])->withSum('items:price')->get();

echo $invoices[0]->id;
echo $invoices[0]->items_price_sum;
```

In addition, using the `loadSum` method, you may load a relationship sum columns after the parent model has already been retrieved:

```
$invoice = Invoice::first();
$invoice->loadSum('items:price');
```

If you need to set additional query constraints on the eager loading query, you may pass an array keyed by the relationships you wish to load. The array values should be Closure instances which receive the query builder instance:

```
$invoice = Invoice::first();
$invoice->loadSum(['items:price' => function ($query) {
    $query->where('price', '>', 5);
}]);
```

And of course it is all compatible with scopes in models.

### Sorting

[](#sorting)

If you want to sort by field in a related model, simply use the following method:

```
$invoices = Invoice::orderByRelation('items:price')->get();
```

or with conditions

```
$invoices = Invoice::orderByRelation(['items:price' => function (Builder $query) {
    $query->where('price', '>', 6);
}, 'desc', 'max'])->get();
```

By default, sorting is by `max` and `desc`, you can choose one of the options `max`, `min`, `sum`, `avg`, `desc`, `acs`.

```
$invoices = Invoice::orderByRelation('items:price', 'asc', 'sum')->get();
```

### Working with columns

[](#working-with-columns)

To add or multiply the required columns use this method:

```
$items = Item::withMath(['invoice_id', 'price'])->get();
echo $items[0]->sum_invoice_id_price;
```

Columns will be summed by default, you can choose one of the options `+`, `-`, `*`, `/` and set a new name.

```
$items = Item::withMath(['invoice_id', 'price', 'price2'], '*', 'new_column')->get();
echo $items[0]->new_column;
```

### Working with dates

[](#working-with-dates)

A more convenient way to select by dates. By default, sorting is by `created_at`.

```
$invoices = Invoice::whereCurrentYear('column_name')->get();
$invoices = Invoice::whereCurrentMonth()->get();
$invoices = Invoice::whereCurrentDay()->get();
```

### Load latest or oldest relation

[](#load-latest-or-oldest-relation)

Imagine you want to get a list of 50 accounts, each with 100 items. By default, you will get 5000 positions and select the first ones for each account. PHP smokes nervously on the sidelines.
Wow! Now you can load only one latest or oldest related model:

```
$invoices = Invoice::all();
$invoices->loadOneLatest('items');
$invoices->loadOneOldest('items');
```

or with conditions

```
$invoices->loadOneLatest(['items' => function ($query) {
    $query->orderBy('id', 'desc')->where('price', 'remember(now()->addDay())->posts()->get();

// You can also pass the number of seconds if you like
// (before Laravel 5.8 this will be interpreted as minutes).
Invoice::withSum('items:price')->remember(60 * 60 * 24)->get();
```

A more detailed description [is here](https://github.com/Alexmg86/laravel-sub-query/wiki/Cache)

### Sugar

[](#sugar)

I got tired of writing some things in detail and I decided to remove them in methods.
You can see [it here](https://github.com/Alexmg86/laravel-sub-query/wiki/Some-sugar)

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity41

Moderate usage in the ecosystem

Community11

Small or concentrated contributor base

Maturity61

Established project with proven stability

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

Recently: every ~22 days

Total

24

Last Release

1851d ago

PHP version history (2 changes)v1.0PHP &gt;=7.2

v1.7.5PHP &gt;=5.6.4

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

cachingdatetimelaravellimitorderbyrelationphprelationship-sumrelationshipssortsubquerywithavgwithmaxwithminwithsumphplaravelquerysubwithSumwithMaxwithMinwithAvgorderByRelationlimit relation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alexmg86-laravel-sub-query/health.svg)

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

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[awssat/laravel-visits

Laravel Redis visits counter for Eloquent models

975163.6k2](/packages/awssat-laravel-visits)[imanghafoori/laravel-widgetize

A minimal yet powerful package to give a better structure and caching opportunity for your Laravel apps.

909137.9k12](/packages/imanghafoori-laravel-widgetize)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11120.2M21](/packages/anourvalar-eloquent-serialize)[swayok/alternative-laravel-cache

Replacements for Laravel's redis and file cache stores that properly implement tagging idea. Powered by cache pool implementations provided by http://www.php-cache.com/

202541.1k6](/packages/swayok-alternative-laravel-cache)[kompo/kompo

Laravel &amp; Vue.js FullStack Components for Rapid Application Development

11812.4k21](/packages/kompo-kompo)

PHPackages © 2026

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