You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10使用fromData方法发送PDF附件邮件报错排查

解决Laravel邮件类中Undefined property: App\Mail\CustomerAppointment::$pdf错误

错误根源是CustomerAppointment邮件类未显式声明$pdf和$customer公共属性。虽然你在构造函数里给这两个属性赋值了,但PHP会将其视为动态属性,Laravel的Mailable类在队列序列化或属性访问时,需要明确的类属性定义才能正常识别。

修复步骤及代码调整

  1. 在邮件类中添加$pdf和$customer的公共属性声明
  2. 修正content方法中with参数的格式(必须传递数组)
  3. 控制器中视图路径改用正斜杠(兼容多操作系统)

修改后的Controller代码

$customer = Customer::findOrFail(session('customerid'));

// 视图路径用正斜杠,避免Windows路径解析问题
$pdf = PDF::loadView('PDF/customerappointmentpdf', compact(['data', 'customer', 'appointment']));

$mailData = [
    'customer' => $customer,
    'pdf' => $pdf,
];
Mail::to($customer)->queue(new CustomerAppointment($mailData));

修改后的CustomerAppointment邮件类代码

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class CustomerAppointment extends Mailable
{
    use Queueable, SerializesModels;

    // 显式声明公共属性,让Laravel能正确识别
    public $customer;
    public $pdf;
  
    public function __construct($mailData)
    {
        $this->pdf = $mailData['pdf'];
        $this->customer = $mailData['customer'];
    }

    public function envelope()
    {
        return new Envelope(
            subject: '客户预约通知',
        );
    }

    public function content()
    {
        return new Content(
            markdown: 'emails.customerappointment',
            // with必须是数组,传递需要的变量到邮件视图
            with: [
                'customer' => $this->customer,
                // 若邮件视图不需要PDF,可删除此行
                // 'pdf' => $this->pdf,
            ]
        );
    }

    public function attachments()
    {
        return [
            Attachment::fromData(fn () => $this->pdf->output(), 'customerappointmentpdf.pdf')
                ->withMime('application/pdf'),
        ];
    }
}

补充说明

  • 显式声明属性后,Laravel可正确处理属性的序列化与访问,彻底解决Undefined property错误
  • content方法的with参数必须为数组,用于给邮件Markdown视图传递变量,按需添加即可
  • 控制器中改用正斜杠的视图路径,能避免跨操作系统的路径解析问题

内容的提问来源于stack exchange,提问作者newdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:10:23