Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Lazy Mysql Laravel Package

zara-4/laravel-lazy-mysql

Laravel package for MySQL that delays/queues queries until needed, helping reduce eager database work and improving performance. Useful for batching, deferred execution, and controlling when SQL actually runs in your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zara-4/laravel-lazy-mysql
    

    Add to config/app.php under providers:

    Zara4\LazyMysql\Eloquent\LazyMysqlServiceProvider::class,
    
  2. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Zara4\LazyMysql\Eloquent\LazyMysqlServiceProvider"
    

    Update config/lazy-mysql.php with your MySQL connection details.

  3. First Use Case: Extend your Eloquent model to use lazy loading:

    use Zara4\LazyMysql\Eloquent\Model;
    
    class User extends Model
    {
        protected $connection = 'lazy_mysql';
    }
    

    Now queries will execute only when data is accessed (e.g., User::all() won’t hit the DB until iterated).


Implementation Patterns

Lazy Query Builder

  • Deferred Execution:
    $users = User::where('active', true)->orderBy('name');
    // No DB hit yet. Only executes when:
    foreach ($users as $user) { ... } // Triggers query
    
  • Chaining with Lazy Collections:
    $activeUsers = User::where('active', true)->lazy();
    $filtered = $activeUsers->filter(fn($u) => $u->role === 'admin');
    

Model Integration

  • Lazy Relationships:
    class Post extends Model
    {
        public function author()
        {
            return $this->belongsTo(User::class)->lazy();
        }
    }
    // Accesses author data only when needed:
    $post->author->name; // Triggers lazy-loaded relationship query
    

Workflows

  1. Batch Processing: Useful for large datasets (e.g., CSV exports):
    User::all()->lazy()->each(function ($user) {
        // Process one user at a time without loading all into memory
    });
    
  2. API Responses: Return lazy collections to clients for partial data loading:
    return response()->json(User::where('active', true)->lazy());
    

Integration Tips

  • Hybrid Queries: Mix eager (with()) and lazy loading for performance:
    User::with('posts')->lazy()->take(100);
    
  • Custom Lazy Collections: Extend Zara4\LazyMysql\Eloquent\LazyCollection for domain-specific logic.

Gotchas and Tips

Pitfalls

  1. N+1 Queries: Lazy loading can inadvertently trigger N+1 queries if relationships are accessed in loops:

    // Bad: Triggers N queries
    foreach (User::all() as $user) {
        $user->posts; // Each post() call hits DB
    }
    

    Fix: Use with() for known relationships or batch access.

  2. Memory Leaks: Lazy collections hold queries until iterated. Avoid storing them in session/cache without executing.

  3. Transaction Scope: Lazy queries may not respect transactions if executed outside the transaction block. Ensure queries run within:

    DB::transaction(function () {
        User::where(...)->lazy()->each(...);
    });
    

Debugging

  • Query Logging: Enable Laravel’s query logging to inspect deferred queries:
    DB::enableQueryLog();
    User::all()->lazy()->first(); // Check last query in `DB::getQueryLog()`
    
  • Connection Issues: Verify lazy-mysql.php config matches your MySQL setup. Test with:
    DB::connection('lazy_mysql')->getPdo();
    

Tips

  1. Performance Tuning:

    • Use cursor() for very large datasets to avoid memory spikes:
      User::all()->lazy()->cursor();
      
    • Limit lazy collections with take() or skip():
      User::where(...)->lazy()->take(500);
      
  2. Extension Points:

    • Override Zara4\LazyMysql\Eloquent\Builder to add custom lazy methods.
    • Hook into Zara4\LazyMysql\Eloquent\LazyCollection::macro() for reusable logic.
  3. Testing: Mock lazy queries in tests by overriding the cursor() method:

    $mock = Mockery::mock(User::class);
    $mock->shouldReceive('cursor')->andReturn([new User(), new User()]);
    
  4. Legacy Code: If mixing with eager-loaded models, explicitly cast to lazy:

    $users = User::where(...)->get()->lazy(); // Force lazy behavior
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony