Looking to hire Laravel developers? Try LaraJobs
This package is not available.

laravel-eager-loaders maintained by joggapp

Description
Configurable eager loading for the Laravel PHP Framework
Author
Last update
2026/03/20 11:07 (dev-master)
License
Links
Downloads
13
Tags

Comments
comments powered by Disqus

Introduction

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);