Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thebigk's avatar
Level 13

Laravel "cursor()" and memory issues

I've a large 'Posts' table (~60k entries) and a "Replies" table (~500k entries). I wish to iterate over the post and replies and then conditionally add them to the sitemap file.

I'm making use of the cursor() method in Laravel 6 but it blows off even before it does anything meaningful. Here's what I have -

// Job


$posts = Post::with('replies')->cursor();


foreach( $posts as $post) {
    // Calculate the word count in posts and associated replies
    // If it's below the threshold, continue the loop
       // Add the $post->url to sitemap
}

Now the moment I run it, I get following error -

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 7510792 bytes) in

What am I doing wrong?

0 likes
6 replies
Sinnbeck's avatar

You should probably use collection methods

$posts = Post::with('replies')->cursor()->each(function($post) {
    // Calculate the word count in posts and associated replies
    // If it's below the threshold, continue the loop
       // Add the $post->url to sitemap
});
thebigk's avatar
Level 13

I see. What exactly is the difference? I've seen several examples that do this with foreach.

UPDATE: The above doesn't seem to work. Not sure what's wrong.

Sinnbeck's avatar

This is just based on the fact that all examples uses collection methods in the official documentation (with the exception of the part that actually echos the data after filtering it)

I could very well be wrong, but if you test it and it just works, I might be correct :)

bugsysha's avatar

How many posts and how many replies are there?

Please or to participate in this conversation.