Laravel 8队列启用时出现Ramsey\Uuid序列化兼容错误
启用队列后SendGrid通知抛出Ramsey\Uuid序列化兼容错误
问题背景
我在项目中通过队列发送SendGrid通知,构建通知的代码如下:
$data = [ 'email_message' => $message, 'subject' => $request->subject, 'email' => $request->email ]; $user->notify(new EmailGeneralNotification($data));
通知类代码:
<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use NotificationChannels\SendGrid\SendGridChannel; use NotificationChannels\SendGrid\SendGridMessage; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; // use Illuminate\Queue\SerializesModels; use App\Models\NotificationTemplate; class EmailGeneralNotification extends Notification implements ShouldQueue { use Queueable; // use SerializesModels; protected $data; /** * Create a new notification instance. * * @return void */ public function __construct(array $data) { $this->data = $data; } public function via($notifiable) { return [ SendGridChannel::class, ]; } public function toSendGrid($notifiable) { $reference = 'internal_general_email'; $template = NotificationTemplate::where('reference',$reference)->latest('updated_at')->first(); if(!$template) { dd("No template was found for " . $reference); } return (new SendGridMessage($template->template_id)) /** * optionally set the from address. * by default this comes from config/mail.from * ->from('no-reply@test.com', 'App name') */ /** * optionally set the recipient. * by default it's $notifiable->email: * ->to('hello@example.com', 'Mr. Smith') */ ->payload([ "subject" => (array_key_exists('subject', $this->data)) ? $this->data['subject'] : '', "email_message" => (array_key_exists('email_message', $this->data)) ? $this->data['email_message'] : '', ]); } }
问题现象
移除implements ShouldQueue和use Queueable时,通知发送完全正常;但启用队列后,抛出以下致命错误:
[2022-10-30 08:34:08] local.ERROR: Declaration of Ramsey\Uuid\Uuid::unserialize(string $data): void must be compatible with Serializable::unserialize($serialized) {"exception":"[object] (Symfony\\Component\\ErrorHandler\\Error\\FatalError(code: 0): Declaration of Ramsey\\Uuid\\Uuid::unserialize(string $data): void must be compatible with Serializable::unserialize($serialized) at /var/www/html/vendor/ramsey/uuid/src/Uuid.php:307) [stacktrace] #0 {main} "}
已将PHP升级到8.x、Laravel版本升级到8.83.25,问题仍未解决。
解决方案
升级Ramsey/Uuid版本
Laravel 8.x搭配PHP 8时,需要ramsey/uuid^4.3及以上版本(该版本修复了PHP 8中Serializable接口的兼容性问题),执行命令更新:composer require ramsey/uuid:^4.3确认队列序列化配置
在config/queue.php中,确保序列化驱动为php(Laravel 8默认),避免旧序列化方式引发冲突:'connections' => [ 'database' => [ // 其他配置... 'serializer' => 'php', ], ],恢复SerializesModels trait
对于队列通知,建议启用SerializesModelstrait,它会规范模型序列化逻辑,减少潜在冲突:use Illuminate\Queue\SerializesModels; class EmailGeneralNotification extends Notification implements ShouldQueue { use Queueable, SerializesModels; // 其他代码... }刷新缓存与自动加载
更新依赖后执行以下命令,确保修改生效:composer dump-autoload php artisan cache:clear php artisan queue:restart
内容的提问来源于stack exchange,提问作者cwb
相关产品推荐
相关产品推荐

