PHPackages                             liam-wiltshire/laravel-jit-loader - 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. liam-wiltshire/laravel-jit-loader

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

liam-wiltshire/laravel-jit-loader
=================================

Just In Time relationship loader for Laravel

0.7.0(5y ago)21479.8k↓32.8%11[2 issues](https://github.com/liam-wiltshire/laravel-jit-loader/issues)[2 PRs](https://github.com/liam-wiltshire/laravel-jit-loader/pulls)MITPHPPHP &gt;=7.1.0CI failing

Since Feb 24Pushed 4y ago4 watchersCompare

[ Source](https://github.com/liam-wiltshire/laravel-jit-loader)[ Packagist](https://packagist.org/packages/liam-wiltshire/laravel-jit-loader)[ RSS](/packages/liam-wiltshire-laravel-jit-loader/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (5)Versions (14)Used By (0)

liam-wiltshire/laravel-jit-loader
=================================

[](#liam-wiltshirelaravel-jit-loader)

liam-wiltshire/laravel-jit-loader is an extension to the default Laravel Eloquent model to 'very lazy eager load' relationships with performance comparable with eager loading.

Installation
============

[](#installation)

liam-wiltshire/laravel-jit-loader is available as a composer package: `composer require liam-wiltshire/laravel-jit-loader`

Once installed, use the `\LiamWiltshire\LaravelJitLoader\Concerns\AutoloadsRelationships` trait in your model, or have your models extend the `\LiamWiltshire\LaravelJitLoader\Model` class instead of the default eloquent model, and JIT loading will be automatically enabled.

Very Lazy Eager Load?
=====================

[](#very-lazy-eager-load)

In order to avoid [N+1 issues](https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/), you'd normally load your required relationships while building your collection:

```
$books = App\Book::with(['author', 'publisher'])->get();
```

Or otherwise after the fact, but before use:

```
$books = App\Book::all();

if ($someCondition) {
    $books->load('author', 'publisher');
}
```

In some situations however, this may not be possible - perhaps front-end developers are able to make changes to templates without touching the code, or perhaps during development you know don't which relationships you'll need anyway. This change will track if your models belong to a collection, and if they do and a relationship is called that hasn't already been loaded, the relationship will be loaded across the whole collection just in time for use.

Does This Work?
===============

[](#does-this-work)

This is used in a number of production applications with no issues. It's also been tested against a (rather constructed) test, pulling out staff, companies and addresses - while this isn't a 'real life' representation, it should give an idea of what it can do:

```
    public function handle()
    {
        //Count the number of queries
        $querycount = 0;
        DB::listen(function ($query) use (&$querycount) {
            $querycount++;
        });

        $startTime = microtime(true);

        $staff = Staff::where('name', 'LIKE', 'E%')->orWhere('name', 'LIKE', 'P%')->get();

        /**
         * @var Staff $st
         */
        foreach ($staff as $st) {
            /**
             * @var Company $company
             */
            $company = $st->company;
            echo "\n\nName: {$st->name}\n";
            echo "Company Name: {$company->name}\n";
            foreach ($company->address as $address) {
                echo "Addresses: {$address->address_1}, ";
            }
        }

        $endTime = microtime(true);

        echo "\n\n=========================\n\n";
        echo "Queries Run: {$querycount}\n";
        echo "Execution Time: " . ($endTime - $startTime) . "\n";
        echo "Memory:" . memory_get_peak_usage(true)/1024/1024 . "MiB";
        echo "\n\n";
    }
```

Running this locally against a database with 200 companies, 1157 addresses and 39685 staff:

Without JIT Loading:
--------------------

[](#without-jit-loading)

Queries Run: 10739
Execution Time: 17.090859889984
Memory: 70MiB

With JIT Loading:
-----------------

[](#with-jit-loading)

Queries Run: 3
Execution Time: 1.7261669635773
Memory: 26MiB

'Proper' Eager Loading:
-----------------------

[](#proper-eager-loading)

Queries Run: 3
Execution Time: 1.659285068512
Memory: 26MiB

Logging
=======

[](#logging)

As you can see the different between JIT loading and traditional eager loading is small (c. 0.067 seconds in our above test), so you can likely rely on JIT loader to protect you.

However, if you want to log when the JIT loader is used so that you can do back and correct them later, you can add a `$logChannel` property to your models to ask the trait to log into that channel as configured in Laravel

```
class Address extends Model
{
    use AutoloadsRelationships;

    /**
     * @var string
     */
    protected $logChannel = 'jit-logger';

    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}
```

Limitations
===========

[](#limitations)

This is an early release based on specific use cases. At the moment the autoloading will only be used when the relationship is loaded like a property e.g. `$user->company->name` instead of `$user->company()->first()->name`. I am working on supporting relations loaded in alternate ways, however there is more complexity in that so there isn't a fixed timescale as of yet!

With any eager loading, a sufficiently large collection can cause memory issues. The JIT model specifies a threshold for autoloading. This is set to 6000 by default, but can be changed by overriding the `$autoloadThreshold` property on a model-by-model basis.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity47

Moderate usage in the ecosystem

Community19

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 74.2% 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 ~78 days

Recently: every ~128 days

Total

9

Last Release

2014d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10179637?v=4)[Liam Wiltshire](/maintainers/liam-wiltshire)[@liam-wiltshire](https://github.com/liam-wiltshire)

---

Top Contributors

[![liam-wiltshire](https://avatars.githubusercontent.com/u/10179637?v=4)](https://github.com/liam-wiltshire "liam-wiltshire (46 commits)")[![staudenmeir](https://avatars.githubusercontent.com/u/1853169?v=4)](https://github.com/staudenmeir "staudenmeir (7 commits)")[![fridzema](https://avatars.githubusercontent.com/u/8180660?v=4)](https://github.com/fridzema "fridzema (3 commits)")[![mikemand](https://avatars.githubusercontent.com/u/745184?v=4)](https://github.com/mikemand "mikemand (2 commits)")[![svenluijten](https://avatars.githubusercontent.com/u/11269635?v=4)](https://github.com/svenluijten "svenluijten (2 commits)")[![georgehanson](https://avatars.githubusercontent.com/u/23167178?v=4)](https://github.com/georgehanson "georgehanson (1 commits)")[![davidjr82](https://avatars.githubusercontent.com/u/4275886?v=4)](https://github.com/davidjr82 "davidjr82 (1 commits)")

---

Tags

eager-loadingeloquenteloquent-relationshipslaravel

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/liam-wiltshire-laravel-jit-loader/health.svg)

```
[![Health](https://phpackages.com/badges/liam-wiltshire-laravel-jit-loader/health.svg)](https://phpackages.com/packages/liam-wiltshire-laravel-jit-loader)
```

###  Alternatives

[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[staudenmeir/eloquent-json-relations

Laravel Eloquent relationships with JSON keys

1.1k5.8M24](/packages/staudenmeir-eloquent-json-relations)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[gearbox-solutions/eloquent-filemaker

A package for getting FileMaker records as Eloquent models in Laravel

6454.8k2](/packages/gearbox-solutions-eloquent-filemaker)[cybercog/laravel-ownership

Laravel Ownership simplify management of Eloquent model's owner.

9126.6k3](/packages/cybercog-laravel-ownership)

PHPackages © 2026

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