Laravel Mail ::仅在不为null时附加文件

时间:2018-10-28 15:14:10

标签: php laravel email vue.js

大家好,我有一封邮件,其中的文件字段可为空(不是必需的),但是由于这个原因,当我尝试附加一个空的uploadFile时,出现以下错误:

“消息未定义索引:uploadFile”

我的问题是,有一种不错的Laravel方法将文件附加到邮件吗(如果存在)?

这是我的邮件构建方法:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ClientContactMail extends Mailable
{
    use Queueable, SerializesModels;
    
    public $mailData;

    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }

    
    
    
    public function build()

    {
        return $this->markdown('emails.client-contact')
        ->from($this->mailData['sender'], $this->mailData['appName'])
        ->subject($this->mailData['subject'])
        ->attach($this->mailData['uploadFile'], ['as' => $this->mailData['fileName'], 'mime' => $this->mailData['mimeType']]);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用简单的if语句解决此问题,如果文件存在,请附加它。

public function build()

{
    $mail = $this->markdown('emails.client-contact')
        ->from($this->mailData['sender'], $this->mailData['appName'])
        ->subject($this->mailData['subject']);

    if (isset($this->mailData['uploadFile'])) {\
        $mail = $mail->attach($this->mailData['uploadFile'], ['as' => $this->mailData['fileName'], 'mime' => $this->mailData['mimeType']])
    }

    return $mail;
}