PHPackages                             dossierdata/eloquent-has-by-non-dependent-subquery - 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. dossierdata/eloquent-has-by-non-dependent-subquery

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

dossierdata/eloquent-has-by-non-dependent-subquery
==================================================

Convert has() and whereHas() constraints to non-dependent subqueries.

v2.0.4(3mo ago)030MITPHPPHP ^7.3 || ^8.0

Since Jun 28Pushed 3mo agoCompare

[ Source](https://github.com/dossierdata/eloquent-has-by-non-dependent-subquery)[ Packagist](https://packagist.org/packages/dossierdata/eloquent-has-by-non-dependent-subquery)[ RSS](/packages/dossierdata-eloquent-has-by-non-dependent-subquery/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (7)Versions (11)Used By (0)

Eloquent Has By Non-dependent Subquery [![Build Status](https://github.com/mpyw/eloquent-has-by-non-dependent-subquery/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/mpyw/eloquent-has-by-non-dependent-subquery/actions) [![Coverage Status](https://camo.githubusercontent.com/35d8a26c74434855ae03e764f34db9567966666f47d8047aaf114cd073b0d2c6/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d7079772f656c6f7175656e742d6861732d62792d6e6f6e2d646570656e64656e742d73756271756572792f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/mpyw/eloquent-has-by-non-dependent-subquery?branch=master) [![Scrutinizer Code Quality](https://camo.githubusercontent.com/e7ccb9b9fd700dcf7d76ea23967c4bf4659378ac150dd1daf01d8d4f43704c5a/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d7079772f656c6f7175656e742d6861732d62792d6e6f6e2d646570656e64656e742d73756271756572792f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/mpyw/eloquent-has-by-non-dependent-subquery/?branch=master)
==============================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#eloquent-has-by-non-dependent-subquery---)

Convert `has()` and `whereHas()` constraints to non-dependent subqueries.

Important

**NOTICE: Postgres' optimizer is very smart and covers JOIN optimization for dependent (correlated) subqueries. Therefore, this library is mainly targeted at MySQL which has a poor optimizer.**

Caution

**UPDATE: [MySQL's optimizer has also been updated in version `8.0.16`](https://zenn.dev/yumemi_inc/articles/e8ca9535dba0b6) to include optimizations similar to PostgreSQL. This library is no longer maintained.**

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

[](#requirements)

- PHP: `^7.3 || ^8.0`
- Laravel: `^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0`

Installing
----------

[](#installing)

```
composer require mpyw/eloquent-has-by-non-dependent-subquery
```

#### Suggestion

[](#suggestion)

You can install **[wimski/laravel-ide-helper-hook-eloquent-has-by-non-dependent-subquery](https://github.com/wimski/laravel-ide-helper-hook-eloquent-has-by-non-dependent-subquery)** to work with [Laravel IDE Helper](https://github.com/barryvdh/laravel-ide-helper).

Motivation
----------

[](#motivation)

Suppose you have the following relationship:

```
class Post extends Model
{
    use SoftDeletes;

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}
```

```
class Comment extends Model
{
    use SoftDeletes;
}
```

If you use `has()` constraints, your actual query would have **dependent subqueries**.

```
$posts = Post::has('comments')->get();
```

```
select * from `posts` where exists (
  select * from `comments`
  where `posts`.`id` = `comments`.`post_id`
    and `comments`.`deleted_at` is null
) and `posts`.`deleted_at` is null
```

These subqueries may cause performance degradations. This package provides **`Illuminate\Database\Eloquent\Builder::hasByNonDependentSubquery()`** macro to solve this problem: you can easily transform dependent subqueries into non-dependent ones.

```
$posts = Post::hasByNonDependentSubquery('comments')->get();
```

```
select * from `posts`
where `posts`.`id` in (
  select `comments`.`post_id` from `comments`
  where `comments`.`deleted_at` is null
)
and `posts`.`deleted_at` is null
```

API
---

[](#api)

### Signature

[](#signature)

```
Illuminate\Database\Eloquent\Builder::hasByNonDependentSubquery(string|string[] $relationMethod, ?callable ...$constraints): $this
```

```
Illuminate\Database\Eloquent\Builder::orHasByNonDependentSubquery(string|string[] $relationMethod, ?callable ...$constraints): $this
```

```
Illuminate\Database\Eloquent\Builder::doesntHaveByNonDependentSubquery(string|string[] $relationMethod, ?callable ...$constraints): $this
```

```
Illuminate\Database\Eloquent\Builder::orDoesntHaveByNonDependentSubquery(string|string[] $relationMethod, ?callable ...$constraints): $this
```

### Arguments

[](#arguments)

#### `$relationMethod`

[](#relationmethod)

A relation method name that returns a **`Relation`** instance except `MorphTo`.

```
Builder::hasByNonDependentSubquery('comments')
```

You can pass nested relations as an array or a string with dot-chain syntax.

```
Builder::hasByNonDependentSubquery(['comments', 'author'])
```

```
Builder::hasByNonDependentSubquery('comments.author')
```

#### `$constraints`

[](#constraints)

Additional `callable` constraints for relations that take **`Illuminate\Database\Eloquent\Relation`** as the first argument.

```
Builder::hasByNonDependentSubquery('comments', fn (HasMany $query) => $query->withTrashed())
```

If you are using a union type as of PHP 8.0, the order of types does not matter.

```
// This will work
Builder::hasByNonDependentSubquery('comments', fn (HasMany|Comment $query) => $query->withTrashed())
// and so will this
Builder::hasByNonDependentSubquery('comments', fn (Comment|HasMany $query) => $query->withTrashed())
```

The first closure corresponds to `comments` and the second one corresponds to `author`.

```
Builder::hasByNonDependentSubquery(
    'comments.author',
    fn (HasMany $query) => $query->withTrashed(),
    fn (BelongsTo $query) => $query->whereKey(123)
)
```

Feature Comparison
------------------

[](#feature-comparison)

Feature[`mpyw/eloquent-has-by-join`](https://github.com/mpyw/eloquent-has-by-join)`mpyw/eloquent-has-by-non-dependent-subquery`Minimum Laravel version5.65.8Argument of optional constraints`Illuminate\Database\Eloquent\Builder``Illuminate\Database\Eloquent\Relations\*`
(`Builder` can be also accepted by specifying argument type)[Compoships](https://github.com/topclaudy/compoships) support✅❌No subqueries✅❌
(Performance depends on database optimizers)No table collisions❌
(Sometimes you need to give aliases)✅No column collisions❌
(Sometimes you need to use qualified column names)✅OR conditions❌✅Negative conditions❌✅Counting conditions❌❌`HasOne`✅✅`HasMany`❌✅`BelongsTo`✅✅`BelongsToMany`❌✅`MorphOne`✅✅`MorphMany`❌✅`MorphTo`❌❌`MorphMany`❌✅`MorphToMany`❌✅`HasOneThrough`❌✅`HasManyThrough`❌✅

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance80

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 89.3% 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 ~226 days

Recently: every ~456 days

Total

10

Last Release

106d ago

Major Versions

v1.1.1 → v2.0.02021-01-25

PHP version history (3 changes)v1.0.0PHP ^7.1

v1.1.1PHP ^7.1 || ^8.0

v2.0.0PHP ^7.3 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/276ac615994962c132eb8c6af822850eecf36cf6482969c673fe0d95a1266a9d?d=identicon)[lucasvdh](/maintainers/lucasvdh)

---

Top Contributors

[![mpyw](https://avatars.githubusercontent.com/u/1351893?v=4)](https://github.com/mpyw "mpyw (25 commits)")[![hexium310](https://avatars.githubusercontent.com/u/10758173?v=4)](https://github.com/hexium310 "hexium310 (1 commits)")[![lucasvdh](https://avatars.githubusercontent.com/u/4311594?v=4)](https://github.com/lucasvdh "lucasvdh (1 commits)")[![wimski](https://avatars.githubusercontent.com/u/12373573?v=4)](https://github.com/wimski "wimski (1 commits)")

---

Tags

laraveldatabaseeloquentquerybuilderilluminatemacrodependentwhereHashas

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dossierdata-eloquent-has-by-non-dependent-subquery/health.svg)

```
[![Health](https://phpackages.com/badges/dossierdata-eloquent-has-by-non-dependent-subquery/health.svg)](https://phpackages.com/packages/dossierdata-eloquent-has-by-non-dependent-subquery)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[mpyw/laravel-local-class-scope

A tiny macro that reuse a global scope class as a local scope

24102.6k](/packages/mpyw-laravel-local-class-scope)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[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)

PHPackages © 2026

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