PromptHub
Laravel Advanced 30 views

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

30

Related Errors