Skip to content

Conversation

litvinchuk
Copy link
Contributor

@litvinchuk litvinchuk commented Apr 9, 2025

In the current implementation of #53655, serializing models with automatic relation loading enabled can cause the error: Serialization of 'Closure' is not allowed

This occurs because the closure used for relation loading cannot be serialized. This fix resolves the issue by removing the closure before serialization and reinstating it in the __wakeup method if Model::automaticallyEagerLoadRelationships is enabled.

In the case of opt-in usage, the developer needs to explicitly call withRelationshipAutoloading() again after deserialization to re-enable the feature I this model.

With this fix, the following should now work without errors:

Model::automaticallyEagerLoadRelationships();

$user = Cache::remember('user', 60, fn () => User::find(1));

foreach ($user->comments as $comment) {
    //
}

@litvinchuk litvinchuk marked this pull request as draft April 9, 2025 18:55
@litvinchuk litvinchuk marked this pull request as ready for review April 9, 2025 19:08
@taylorotwell taylorotwell merged commit f70f69b into laravel:12.x Apr 10, 2025
58 checks passed
@decadence
Copy link
Contributor

I wonder when this fix will be released 🤔

@AhmedAlaa4611
Copy link
Contributor

Can we make Model::automaticallyEagerLoadRelationships(); the default behavior of the framework?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants