Laravel 5.3 - Attach Multiple Files To Mailables

六眼飞鱼酱① 提交于 2020-01-10 18:17:14

问题


How does one go about attaching multiple files to laravel 5.3 mailable?

I can attach a single file easily enough using ->attach($form->filePath) on my mailable build method. However, soon as I change the form field to array I get the following error:

basename() expects parameter 1 to be string, array given

I've searched the docs and also various search terms here on stack to no avail. Any help would be greatly appreciated.

Build Method:

public function build()
{
    return $this->subject('Employment Application')
                ->attach($this->employment['portfolio_samples'])
                ->view('emails.employment_mailview');
}

Mail Call From Controller:

Mail::to(config('mail.from.address'))->send(new Employment($employment));

回答1:


You should store your generated email as a variable, then you can just add multiple attachments like this:

public function build()
{
    $email = $this->view('emails.employment_mailview')->subject('Employment Application');

    // $attachments is an array with file paths of attachments
    foreach($attachments as $filePath){
        $email->attach($filePath);
    }
    return $email;
}

In this case your $attachments variable should be an array with paths to files:

$attachments = [
    // first attachment
    '/path/to/file1',

    // second attachment
    '/path/to/file2',
    ...
];


Also you can attach files not only by file paths, but with MIME type and desired filename, see documentation about second case of use for the attachment method: https://laravel.com/docs/master/mail#attachments

For example, your $attachments array can be something like this:

$attachments = [
    // first attachment
    'path/to/file1' => [
        'as' => 'file1.pdf',
        'mime' => 'application/pdf',
    ],

    // second attachment
    'path/to/file12' => [
        'as' => 'file2.pdf',
        'mime' => 'application/pdf',
    ],

    ...
];

After you can attach files from this array:

// $attachments is an array with file paths of attachments
foreach($attachments as $filePath => $fileParameters){
    $email->attach($filePath, $fileParameters);
}


来源:https://stackoverflow.com/questions/42848363/laravel-5-3-attach-multiple-files-to-mailables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!