Back to articles
->cursor() or -> chunk()

->cursor() or -> chunk()

via Dev.to WebdevViktor Le

In Laravel, the cursor() method is used to iterate through large database datasets efficiently by keeping only a single record in memory at a time. Unlike get(), which loads the entire result set into an array, cursor() uses PHP generators to yield records one by one. 1. Basic Usage You can call cursor() at the end of an Eloquent or Query Builder chain. It returns a LazyCollection instance that you can loop through. use App\Models\User ; foreach ( User :: where ( 'active' , true ) -> cursor () as $user ) { // Process one user at a time echo $user -> name ; } 2. Key Characteristics Single Query Execution : Unlike chunk(), which executes a new query for every batch of records, cursor() executes only one SQL query against the database. Memory Efficiency : It significantly reduces memory usage because it doesn't build a massive collection of all retrieved objects in PHP memory. Lazy Collections : Starting from Laravel 6.0, cursor() returns a LazyCollection, allowing you to chain collection

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
2 views

Related Articles