In an earlier tip, I showed the failure mode in Laravel 13's hardened cache, where cached objects come back as __PHP_Incomplete_Class instead of the class you were expecting.
So what should you do if your app caches objects today?
The instinct might be to just revert to the prior non-hardened behavior, but I don't think that's the best way.
And you don't need to do a massive refactor to replace cached objects with a simpler data type. That might be a reasonable approach in a smaller app, but in a large app this could quickly spiral into a huge project.
For most large apps, my recommendation is instead to implement a targeted allow-list with just the classes you've identified in your app:
// config/cache.php
'serializable_classes' => [stdClass::class, SomeExpensiveObject::class],
But what if you forgot something? In a giant app, it's easy to miss one use of a Carbon instance, a collection, or some object you wrapped years ago.
Shortly after this cache-hardening feature was released, a new method was added to detect and handle these silent failures:
// in a service provider
Cache::handleUnserializableClassUsing(function (string $key, ?string $class) {
Log::warning(sprintf('Cache hit [%s] returned unserializable class [%s]', $key, $class));
});
In this example, we log these potentially silent failures, but you could do something else to react to the failed deserialization.
Note that this callback is just a notification hook. Your code still receives the broken object, so the failure mode we covered earlier doesn't change, but now you have visibility. If you'd rather fail loudly right at the cache call, you could throw an exception from the callback instead.
Each log entry includes the cache key and the class name, so you can decide whether to add that class to the allow-list or rework that one call site. This small addition to your app gives you the confidence to keep the tighter security posture.
Here to help,
Joel
P.S. Wondering how this advice applies to your app? These are exactly the kinds of trade-offs we talk through every day in the Mastering Laravel community.