Laravel 11 + Livewire表单数据无法传递至邮件模板问题求助
问题排查与修复方案
1. 修正Livewire组件数据获取方式
Livewire组件中,wire:model绑定的是组件的public属性,不需要通过Request $request获取数据,直接使用$this->属性名即可。你的submit方法里用$request->first_name可能无法正确拿到Livewire绑定的值,改成直接从组件属性读取:
public function submit() { $this->validate(); // 直接从组件属性获取数据,而非Request $data = [ 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'nominee_name' => $this->nominee_name ]; // 后续创建模型、发送邮件等代码保持不变... }
同时确保你的Livewire组件顶部定义了对应的public属性:
class YourComponent extends Component { public $first_name; public $last_name; public $nominee_name; // 其他需要绑定的表单属性... }
2. 修复Mailable类的配置错误
你的ThankYouSelfMailable存在两处问题:
build方法中->with($this->data, $this->data)用法错误,with方法只需传递一次关联数组;- Laravel 9+的Mailable同时使用
build和content方法会导致视图数据传递冲突,建议移除build方法,依赖content和public属性自动传递数据。
修正后的Mailable类:
class ThankYouSelfMailable extends Mailable { use Queueable, SerializesModels; public $data; /** * Create a new message instance. */ public function __construct($data) { $this->data = $data; } /** * Get the message envelope. */ public function envelope(): Envelope { return new Envelope( subject: 'Thank You For Submitting', ); } /** * Get the message content definition. */ public function content(): Content { return new Content( view: 'emails.thank_you_self_nominator', ); } /** * Get the attachments for the message. * * @return array<int, \Illuminate\Mail\Mailables\Attachment> */ public function attachments(): array { return []; } }
说明:因为$data是public属性,Laravel会自动将其传递到邮件视图中,无需额外调用with方法。
3. 验证邮件视图的变量调用
你的邮件视图中使用{{$data['first_name']}}是正确的(因为$data是数组),如果想简化写法,可以在Mailable中单独传递每个属性:
// Mailable类中替换public $data为单独属性 public $first_name; public $last_name; public function __construct($data) { $this->first_name = $data['first_name']; $this->last_name = $data['last_name']; }
然后视图中直接使用{{$first_name}} {{$last_name}},写法更直观。
4. 额外检查:Livewire组件的验证规则
确保你的组件中定义了正确的验证规则,避免因验证失败导致数据无法正常传递:
protected $rules = [ 'first_name' => 'required|string', 'last_name' => 'required|string', // 其他表单字段的验证规则... ];
内容的提问来源于stack exchange,提问作者Gregory Rothstein
相关产品推荐
相关产品推荐

