SerializationException
Failed to serialize or unserialize data for caching, queues, or sessions.
Explanation
SerializationException occurs when Laravel cannot serialize or unserialize data. This commonly happens when trying to cache or queue objects that contain unserializable resources like database connections, file handles, or closures. Laravel's cache and queue systems rely heavily on PHP serialization. If an object has __serialize() issues or contains properties that cannot be represented in a serialized form, this exception is thrown. It can also occur when cache drivers are changed and old cached data is incompatible.
Common Causes
- Caching objects with unserializable resources
- Changing class structure with existing cache
- Caching closures without proper package
- Queue driver configuration issue
- Incompatible cache driver format
Solution
Avoid caching or queueing objects with database connections or file handles. Implement the __sleep() and __wakeup() methods to control which properties are serialized. Use the SerializesModels trait on queued jobs to serialize only the model ID. Clear your cache and sessions when changing class structures. For closures in cache, use the SerializableClosure package. Check that the serialize() and unserialize() functions work with your data outside of Laravel first.
Code Example
// This fails because PDO is not serializable
$pdo = DB::connection()->getPdo();
cache()->set('pdo', $pdo); // SerializationException!
// Fix: Cache only serializable data
$connectionConfig = config('database.connections.mysql');
cache()->set('db_config', $connectionConfig);
// For queued jobs, use SerializesModels
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SendEmail implements ShouldQueue
{
use Dispatchable;
public function __construct(public User $user) {}
public function handle(): void
{
// $user is serialized as just the ID and re-fetched
}
}
Error Information
Language
php
Framework
laravel
Difficulty
Advanced
Views
133
Related Errors
PHP
Type Error: Return Type Must Be Compatible
A method override has a return type that conflicts with the parent class or interface.
500
Laravel
Laravel 500 Internal Server Error
A generic server-side error indicating something went wrong during request processing.
Database
Lock Wait Timeout Exceeded
A database query waited too long for a lock held by another transaction.
PHP
Headers Already Sent
The code tries to send HTTP headers after output has already been sent to the browser.