basanta/lazyloader

Lazy load Laravel Models with or without relationship.

1.0.3 2025-01-22 13:54 UTC

This package is auto-updated.

Last update: 2025-06-22 14:47:23 UTC


README

Lazy load Laravel Models with or without relationship.

use Basanta\LazyLoader\LazyLoader;

Has Many :

$usersWithClients = LazyLoader::make($users)->load(Client::class, 'clients')
    ->on([
        'clients.created_by' => 'id',
        'clients.assigned_to' => 'id'
    ])
    ->multi([
        'clients.email', 'clients.first_name', 'clients.last_name',
    ]);

Has One :

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);

Where :

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->where('users.is_active', '=', 1)
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);

When :

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->when(function($item) {
        // custom logic
        // lazy load user model only when missing
        return empty($item['user']);
    })
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);