If you’ve encountered the following error in your Drupal 10 project:
LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution.
You're not alone. This error can be tricky, especially if your code involves services that have direct or indirect references to the database connection. In this blog, we’ll dive into why this error occurs, and how to refactor your code to prevent it from happening.
Understanding the Problem
The error arises because the database connection is an active resource that manages real-time communication with the database. Objects like these cannot be serialized (i.e., converted to a storable or transferable format) because they represent live resources. When you try to serialize objects that hold references to the database connection or other non-serializable services, you’ll see the LogicException.
In Drupal 10, this problem often occurs when you try to serialize service objects such as EntityTypeManagerInterface or DatabaseConnection as part of a larger object, such as when storing data in a session, queue, or cache.
Example Scenario
Let’s consider a typical use case where you’re working with an order in a custom service: