Laravel+MongoDB环境API调用触发PHP内存耗尽错误
Alright, let's tackle this memory limit issue you're running into with your Laravel app that has 60+ APIs and uses MongoDB. That error message clearly states PHP hit its default 128MB memory limit (134217728 bytes) even when trying to allocate just 88 bytes—so the real problem is your app's already maxing out the allowed memory before reaching that small allocation. Here's how to fix this:
1. Increase PHP's Memory Limit
First, let's give PHP more breathing room. You have a few options here:
- Modify php.ini: Locate your server's
php.inifile (common paths are/etc/php/{version}/apache2/php.ini), find thememory_limitdirective, and bump it up. For example:
After saving, restart Apache to apply changes:memory_limit = 256Msudo service apache2 restart - Laravel Entry File: If you can't edit the global php.ini, add this line at the top of
public/index.phpto apply the limit only to your Laravel app:ini_set('memory_limit', '256M'); - .htaccess: If your Apache setup allows it, add this line to your project's
.htaccessfile:php_value memory_limit 256M
2. Optimize Laravel + MongoDB Code (The Root Cause Fix)
Increasing memory is a quick fix, but you'll want to address why your app is using so much memory in the first place:
- Trim Database Queries: Check your Eloquent (or MongoDB Eloquent) queries. Avoid loading unnecessary columns with
select()(e.g.,User::select('id', 'name')->get()instead ofUser::get()), and be cautious with nestedwith()calls that load too many related records. - Avoid N+1 Queries: Make sure you're eager loading relationships properly instead of querying inside loops. Use
with()for eager loading, orchunk()for processing large datasets without loading everything into memory at once. - Handle MongoDB Cursors Carefully: If you're fetching large datasets from MongoDB, use cursor iteration instead of converting the result to an array immediately. This keeps only a small portion of data in memory at a time.
- Debug Memory Usage: Enable Laravel Debugbar (temporarily in non-production) to see which requests are consuming the most memory. You can also use
memory_get_usage()at key points in your code to pinpoint where memory is being hogged.
3. Tune Apache Configuration
Sometimes the issue isn't just PHP, but Apache's child processes consuming too much memory:
- Adjust
MaxConnectionsPerChildin your Apache config (e.g.,/etc/apache2/apache2.conf) to limit how many requests a child process handles before restarting. For example:
This ensures memory leaks in Apache processes get cleaned up regularly.MaxConnectionsPerChild 1000
After making these changes, test your APIs again and check /var/log/apache2/error.log—the memory exhaustion errors should disappear. If not, gradually increase the memory limit further while continuing to optimize your code for better memory efficiency.
内容的提问来源于stack exchange,提问作者Sharath

