Custom Eloquent Relations in Laravel Explained | 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 Custom Relations: Building a HasManyThrough Alternative for Complex Joins

 Eloquent Custom Relations: Building a HasManyThrough Alternative for Complex Joins
===================================================================================

 Laravel's built-in relations cover most schemas, but complex domains sometimes need a custom relation class. Learn to build one with proper eager loading, match callbacks, and whereHas support from scratch.

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

ShareCopy linkCopied

 ![Eloquent Custom Relations: Building a HasManyThrough Alternative for Complex Joins](https://cdn.msaied.com/405/9567c07e9cdd10de853dc989784f6c5c.png) 

  On this page +1. [Why Built-In Relations Sometimes Fall Short](#why-built-in-relations-sometimes-fall-short)
2. [Anatomy of an Eloquent Relation](#anatomy-of-an-eloquent-relation)
3. [A Concrete Example: HasManyByCode](#a-concrete-example-hasmanybycode)
4. [Wiring It Into the Model](#wiring-it-into-the-model)
5. [Handling withCount and whereHas](#handling-codewithcountcode-and-codewherehascode)
6. [Key Takeaways](#key-takeaways)

 Why Built-In Relations Sometimes Fall Short
-------------------------------------------

Laravel ships with `HasMany`, `BelongsToMany`, `HasManyThrough`, and friends. They handle 95% of real-world schemas. But occasionally you hit a domain shape that none of them model cleanly — for example, a polymorphic pivot with an extra filtering dimension, or a relation that spans a non-FK column like a `code` string shared across two tables.

The answer is not a raw query shoved into an accessor. The answer is a **proper Eloquent relation class** that participates in eager loading, `with()`, `whereHas()`, and `withCount()`.

Anatomy of an Eloquent Relation
-------------------------------

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

```php
public function addConstraints(): void;
public function addEagerConstraints(array $models): void;
public function match(array $models, Collection $results, string $relation): array;
public function getResults(): mixed;

```

`addConstraints` applies the WHERE clause for a single-model load. `addEagerConstraints` receives the full parent batch and applies an `IN` clause. `match` stitches results back onto each parent model.

A Concrete Example: HasManyByCode
---------------------------------

Imagine `Campaign` has a `tracking_code` column, and `Conversion` also has `tracking_code` — but there is no FK. A `HasManyByCode` relation solves this cleanly.

```php
namespace App\Relations;

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

class HasManyByCode extends Relation
{
    public function __construct(
        protected string $foreignKey,
        protected string $localKey,
        Model $related,
        Model $parent,
    ) {
        parent::__construct($related->newQuery(), $parent);
    }

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

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

        $this->query->whereIn($this->foreignKey, $keys);
    }

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

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

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

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

```

Wiring It Into the Model
------------------------

Add a convenience method on `Campaign` that mirrors how built-in relations are declared:

```php
use App\Relations\HasManyByCode;
use App\Models\Conversion;

class Campaign extends Model
{
    public function conversions(): HasManyByCode
    {
        return new HasManyByCode(
            foreignKey: 'tracking_code',
            localKey: 'tracking_code',
            related: new Conversion(),
            parent: $this,
        );
    }
}

```

Now standard Eloquent APIs work without modification:

```php
// Eager load — single query with whereIn
$campaigns = Campaign::with('conversions')->get();

// Existence check
$active = Campaign::whereHas('conversions', fn ($q) =>
    $q->where('converted_at', '>=', now()->subDays(7))
)->get();

// Count
$campaigns = Campaign::withCount('conversions')->get();

```

Handling `withCount` and `whereHas`
-----------------------------------

These features rely on `getRelationExistenceQuery()`. The default implementation works for simple cases, but if your foreign key lives on the related table you may need to override it:

```php
public function getRelationExistenceQuery(
    Builder $relatedQuery,
    Builder $parentQuery,
    mixed $columns = ['*']
): Builder {
    return $relatedQuery
        ->select($columns)
        ->whereColumn(
            $this->foreignKey,
            $parentQuery->qualifyColumn($this->localKey)
        );
}

```

This single override unlocks `whereHas`, `doesntHave`, and `withCount` for your custom relation.

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

- Extend `Relation` directly; implement `addConstraints`, `addEagerConstraints`, `match`, and `getResults` as a minimum.
- `initRelation` prevents `null` relation errors on models that have no matching rows.
- Override `getRelationExistenceQuery` to unlock `whereHas` and `withCount`.
- Group results by the foreign key in `match` — `groupBy` on a Collection is O(n) and avoids nested loops.
- Custom relations are first-class citizens: they work with `load()`, `loadMissing()`, and API resources.

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

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

  Can a custom relation class be used with Laravel's API resources and `whenLoaded()`?Yes. As long as `setRelation()` is called in `match()` and `initRelation()` seeds an empty collection, `$model-&gt;relationLoaded('conversions')` returns true after eager loading, and `whenLoaded()` in a resource works identically to built-in relations.

   Does this approach work with `loadMissing()` on already-retrieved models?It does. `loadMissing()` calls `addEagerConstraints` on the batch of models that lack the relation, then calls `match()` to hydrate them — the same code path as `with()` during the initial query.

   How do I add default ordering to the custom relation?Apply `$this-&gt;query-&gt;orderBy(...)` inside `addConstraints()`. For eager loads, ordering is applied per-model after `match()` groups results, so you may also sort the collection inside `match()` before calling `setRelation()`.

   ![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 articleLaravel 13: New Features, Helpers, and Practical Upgrade Notes](https://www.msaied.com/public/articles/laravel-13-new-features-helpers-and-practical-upgrade-notes-1) [Next articlePasswordless Sign-In with Fortify Two-Factor Support in Laravel](https://www.msaied.com/public/articles/passwordless-sign-in-with-fortify-two-factor-support-in-laravel)  

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

1. [Why Built-In Relations Sometimes Fall Short](#why-built-in-relations-sometimes-fall-short)
2. [Anatomy of an Eloquent Relation](#anatomy-of-an-eloquent-relation)
3. [A Concrete Example: HasManyByCode](#a-concrete-example-hasmanybycode)
4. [Wiring It Into the Model](#wiring-it-into-the-model)
5. [Handling withCount and whereHas](#handling-codewithcountcode-and-codewherehascode)
6. [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)
