Filament资源HeaderAction附件上传队列报错:无法访问字符串偏移
问题分析
Cannot access offset of type string on string 错误是因为代码中尝试以数组方式访问字符串变量。结合你的场景,问题核心是附件数据格式不匹配或GenericMail类未正确处理附件参数。
解决步骤
1. 修正Filament附件数据提取逻辑
Filament的FileUpload开启multiple()后,返回的$data['attachments']可能是包含文件元数据的二维数组(而非直接的路径字符串数组),需先提取路径:
->action(function (array $data) { // 提取文件路径,兼容单文件/多文件、元数据数组格式 $attachments = array_map(function ($item) { return is_array($item) ? ($item['path'] ?? '') : $item; }, $data['attachments'] ?? []); // 过滤空路径 $attachments = array_filter($attachments); Mail::to($data['recipient'])->queue(new GenericMail( subject: $data['subject'], body: $data['body'], attachments: $attachments )); }),
2. 确保GenericMail的附件属性始终为数组
如果GenericMail未处理单文件场景(传入字符串而非数组),后续代码将其当作数组访问时会报错。修改构造函数:
class GenericMail extends Mailable { public string $subject; public string $body; public array $attachments; public function __construct(string $subject, string $body, mixed $attachments = []) { $this->subject = $subject; $this->body = $body; // 统一转为数组:传入字符串则包装为数组,空值设为空数组 $this->attachments = is_array($attachments) ? $attachments : ($attachments ? [$attachments] : []); } // 原attachments方法保持不变 public function attachments(): array { $attachments = []; foreach ($this->attachments as $filePath) { if (is_string($filePath) && !empty($filePath)) { $attachments[] = Attachment::fromStorage($filePath); } } return $attachments; } }
3. 日志排查(可选)
若问题仍存在,在attachments()方法中添加日志确认数据格式:
public function attachments(): array { // 记录附件数据到日志,方便排查 \Illuminate\Support\Facades\Log::info('Mail attachments data', ['data' => $this->attachments]); $attachments = []; foreach ($this->attachments as $filePath) { if (is_string($filePath) && !empty($filePath)) { $attachments[] = Attachment::fromStorage($filePath); } } return $attachments; }
查看storage/logs/laravel.log文件,根据日志输出调整数据处理逻辑。
内容的提问来源于stack exchange,提问作者Asad Baig
相关产品推荐
相关产品推荐

