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

redbonzai's avatar

Solution for: Maximum function nesting level of '512' reached, aborting! Error

Currently, I am needing to test some model relations so in my model I load its relations using the $with array like so:

protected $with = [
        'user', 'activities', 'defaultMetric', 'metricTemplates', 'valuesPerSet'
    ];

That caused the following debug error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Maximum function nesting level of '512' reached, aborting!

Here is the fix:

If you are using Laravel Homestead, go into your xdebug.ini file under your PHP version like so:

sudo nano /etc/php/7.2/mods-available/xdebug.ini

The xdebug.ini file looks like this for me:

zend_extension=xdebug.so
xdebug.remote_enable = 1
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 512

Change 512 to 1024 ( or a larger number, whatever your memory can afford ).

Then restart nginx and php fpm.

sudo service nginx restart
sudo service php7.2-fpm restart

Voila!

I hope this helps you. I spend too long figuring this out.

Christian

0 likes
4 replies
Snapey's avatar

Thats not correct. There is no way you should need that level of recursion.

The problem is because you have two models both using $with and mentioning the other model. You should be very careful using with because you can hang your application or chew tons of memory.

3 likes
redbonzai's avatar

Hey @Snapey , I really appreciate your response. That is duly noted. I should definitely look into maybe caching this data instead of using the with array.

I also should have stated the caveat of memory usage with this methodology. Have a nice evening.

Christian

Cronix's avatar

@redbonzai Even caching would not be the best solution for this instance. It would just make it go faster, but the problem is still there and increasing the memory is just a workaround, which will come back to bite you.

They key is to not have 2 models both using $with where they're referencing each other. You end up with Model 1 calling Model 2 calling Model 1 calling Model2, etc.

Using $with is indeed handy, and I do it myself with certain relationships (like I need to always load the user profile), but you have to be really careful with the above "self referencing" scenario. This could end up costing you actual money by having to have more resources (memory) so all of your users don't run out. It's better to be efficient and not use more than absolutely necessary, isn't it?

1 like

Please or to participate in this conversation.