joggapp/laravel-eager-loaders

Configurable eager loading for the Laravel PHP Framework

Maintainers

Package info

github.com/JoggApp/laravel-eager-loaders

pkg:composer/joggapp/laravel-eager-loaders

Statistics

Installs: 13

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v3.0.0 2026-03-20 10:07 UTC

This package is auto-updated.

Last update: 2026-05-20 08:39:05 UTC


README

This package makes it easy to load Eloquent model relationships via an associative array of options, usually from a FormRequest class.

Installation

Install the package via Composer:

composer require joggapp/laravel-eager-loaders

Usage

Defining an EagerLoader

Consider a Product model with category, name, and price fields.

We can apply sorting and filtering on these fields by defining a EagerLoader class. To create one, use the following command:

php artisan make:eager-loader PostEagerLoader

This command will create a new EagerLoader class in the App\EagerLoaders directory.

Within this class, you can define the relationships a user is allowed to load:

protected array $allowedIncludes = [
    'comments',
];

Or define a custom relationship:

protected array $allowedIncludes = [
    'flagged_comments',
];

protected array $loaderMap = [
    'flagged_comments' => 'flaggedComments',
];

protected function flaggedComments()
{
    $this->load(['comments' => function ($query) {
        $query->where('flagged', true);
    }]);
}

Using EagerLoader Methods

After defining the EagerLoader, it can be used to load Eloquent model relationships:

use App\Model\Post;
use App\EagerLoaders\PostEagerLoader;

$post = Post::first();

(new PostEagerLoader())
    ->add(['comments'])
    ->applyTo($post);

In this example, we are getting all comments related to the given post.

We can also load all relationshiops by following the example below:

use App\Model\Post;
use App\EagerLoaders\PostEagerLoader;

$post = Post::first();

(new PostEagerLoader())
    ->add(['*'])
    ->applyTo($post);