Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 - Attach Multiple Files To Mailables

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));
like image 383
kash101 Avatar asked Mar 17 '17 02:03

kash101


People also ask

How do I attach multiple files?

When you open the folder where the files are stored, select one and then press and hold the Ctrl Key down while you click each file you want to attach. When you are finished click the Open Button and all of the selected files will be attached.


1 Answers

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);
}
like image 182
Alexander Reznikov Avatar answered Oct 09 '22 19:10

Alexander Reznikov