Custom Eloquent Relations &amp; Query Builder Internals | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Eloquent Without the Magic: Custom Relations and Query Builder Internals

 Eloquent Without the Magic: Custom Relations and Query Builder Internals
=========================================================================

 Go beyond hasMany and belongsTo. Learn how Eloquent relations are built internally, write a custom relation class from scratch, and tap the query builder directly for complex joins without sacrificing type safety.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 24 Jun 2026 · Updated 24 Jun 2026 · 4 min read

ShareCopy linkCopied

 ![Eloquent Without the Magic: Custom Relations and Query Builder Internals](https://cdn.msaied.com/279/2ec9eec2d01575b831b7a9230b2ffd06.png) 

  On this page +1. [Why Bother Going Deeper?](#why-bother-going-deeper)
2. [How a Relation Is Actually Built](#how-a-relation-is-actually-built)
3. [Tapping the Query Builder Directly](#tapping-the-query-builder-directly)
4. [Testing the Custom Relation](#testing-the-custom-relation)
5. [Key Takeaways](#key-takeaways)

 Why Bother Going Deeper?
------------------------

Eloquent's built-in relations cover 90 % of use-cases elegantly. The remaining 10 % — lateral joins, filtered aggregates, multi-column foreign keys — either get shoved into raw SQL strings or balloon into unmaintainable query scopes. Understanding the internals lets you write a proper `Relation` subclass instead, keeping the Eloquent API consistent across your codebase.

---

How a Relation Is Actually Built
--------------------------------

Every relation extends `Illuminate\Database\Eloquent\Relations\Relation`. The two methods you must implement are:

- **`addConstraints()`** — called immediately when the relation is instantiated on a single model, adds the `WHERE` clause for eager loading.
- **`addEagerConstraints(array $models)`** — called during eager loading, replaces the single-model constraint with an `IN (...)` clause across all parent keys.

The third required method is **`initRelation(array $models, string $relation)`** and **`match()`**, which hydrate the loaded records back onto the parent models.

```php
namespace App\Relations;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;

class LatestOfMany extends Relation
{
    public function __construct(
        Builder $query,
        Model $parent,
        protected string $foreignKey,
        protected string $localKey,
        protected string $orderColumn,
    ) {
        parent::__construct($query, $parent);
    }

    public function addConstraints(): void
    {
        if (static::$constraints) {
            $this->query
                ->where($this->foreignKey, $this->parent->{$this->localKey})
                ->orderByDesc($this->orderColumn)
                ->limit(1);
        }
    }

    public function addEagerConstraints(array $models): void
    {
        $keys = collect($models)->pluck($this->localKey)->unique()->values();

        // Use a subquery per parent key to avoid the N+1 trap
        $this->query->whereIn($this->foreignKey, $keys);
    }

    public function initRelation(array $models, $relation): array
    {
        foreach ($models as $model) {
            $model->setRelation($relation, null);
        }
        return $models;
    }

    public function match(array $models, Collection $results, $relation): array
    {
        $dictionary = $results->keyBy($this->foreignKey);

        foreach ($models as $model) {
            $key = $model->{$this->localKey};
            $model->setRelation($relation, $dictionary->get($key));
        }
        return $models;
    }

    public function getResults(): mixed
    {
        return $this->query->first();
    }
}

```

Register it on the parent model:

```php
class Order extends Model
{
    public function latestShipment(): LatestOfMany
    {
        return new LatestOfMany(
            Shipment::query(),
            $this,
            foreignKey: 'order_id',
            localKey: 'id',
            orderColumn: 'dispatched_at',
        );
    }
}

```

Now `Order::with('latestShipment')->get()` works exactly like any built-in relation — no raw SQL leaking into controllers.

---

Tapping the Query Builder Directly
----------------------------------

When you need a covering aggregate without a relation, reach for `withAggregate` or drop to the grammar layer:

```php
// Built-in — generates a correlated subquery
$orders = Order::withSum('items', 'quantity')->get();

// Manual subquery column — same idea, full control
$orders = Order::addSelect([
    'latest_dispatch' => Shipment::select('dispatched_at')
        ->whereColumn('order_id', 'orders.id')
        ->orderByDesc('dispatched_at')
        ->limit(1),
])->get();

```

For window functions, bypass Eloquent entirely and use `DB::table()` with a raw expression, then hydrate manually:

```php
$rows = DB::table('shipments')
    ->selectRaw(
        'order_id,
         dispatched_at,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY dispatched_at DESC) AS rn'
    )
    ->toBase() // returns the underlying QueryBuilder, no Eloquent overhead
    ->get()
    ->where('rn', 1);

```

---

Testing the Custom Relation
---------------------------

With Pest, assert eager loading produces no extra queries:

```php
it('eager-loads latest shipment without N+1', function () {
    $orders = Order::factory(5)->create();
    Shipment::factory()->for($orders->first())->create();

    $queryCount = 0;
    DB::listen(fn () => $queryCount++);

    Order::with('latestShipment')->get();

    expect($queryCount)->toBe(2); // one for orders, one for shipments
});

```

---

Key Takeaways
-------------

- `addConstraints` and `addEagerConstraints` are the two hooks that separate single-model access from eager loading — get them wrong and you reintroduce N+1.
- `match()` is pure PHP array work; keep it O(n) by keying the results collection before the loop.
- `withAggregate` / `addSelect` subqueries are often faster than a join when the aggregate touches only a few rows per parent.
- Always verify query count in tests — a custom relation that silently falls back to N+1 is worse than no relation at all.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [eloquent](https://www.msaied.com/public/articles?search=eloquent)
- [query-builder](https://www.msaied.com/public/articles?search=query-builder)
- [orm](https://www.msaied.com/public/articles?search=orm)

 Frequently asked questions 
---------------------------

  When should I write a custom Relation class instead of using a query scope?Write a custom Relation when you need eager loading support (with/load), want the result hydrated as a model or collection, or need the relation to be chainable with further Eloquent constraints. Query scopes are better for filtering, not for associating related models.

   Does a custom Relation class support lazy eager loading via `$model-&gt;load()`?Yes. As long as you implement addEagerConstraints, initRelation, and match correctly, Laravel's eager loading pipeline treats your class identically to built-in relations, including load(), loadMissing(), and with().

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleRoute Metadata Support and More in Laravel 13.17](https://www.msaied.com/public/articles/route-metadata-support-and-more-in-laravel-1317) [Next articleLaravel Queues: Reliable Job Middleware, Idempotency, and Graceful Failure Handling](https://www.msaied.com/public/articles/laravel-queues-reliable-job-middleware-idempotency-and-graceful-failure-handling)  

   On this page
-------------

1. [Why Bother Going Deeper?](#why-bother-going-deeper)
2. [How a Relation Is Actually Built](#how-a-relation-is-actually-built)
3. [Tapping the Query Builder Directly](#tapping-the-query-builder-directly)
4. [Testing the Custom Relation](#testing-the-custom-relation)
5. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
