Search code examples
phpmysqllaravelhttp-status-code-500

Too many rows causing 500 error?


I have 40k entries in a database, and I am trying to call them using a simple fetch in laravel.

$domains = Domain::where("available", 1)->limit(1000)->get();
return view('domains')
    ->with("domains", $domains);

This works fine up to a few thousand rows. But if I set no limit on the call, I receive a 500 error. I can't fathom why, and I can't work out where I would look to discover how to avoid this issue, I can't seem to find anything in the apache logs, or laravel's own logs located in storage.


Solution

  • You can avoid this issue by leveraging the ->chunk command.

    Domain::where('available', 1)->chunk(200, function($domain){
        //do whatever you would normally be doing with the rows you receive
        // $domain stuff
    });
    

    The purpose of the chunk command is to free up memory after every X iterations of the Model. In this case, I've shown 200.

    Sidenote - As the chunk method uses a Closure as the 2nd argument, ensure you use($your_varaibles);