laravel-eager-loaders maintained by joggapp
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);