How to Make Multiple Attachments to Mail in Laravel 5.6

I want to assume if you are reading this, you are already familiar with Laravel and it’s mailing style. That being settled, let me guide you in my own little way how to attach multiple files to a mail. This guide is very likely to also apply to Laravel 5.4 and 5.5.

This has been tested and proven only on the Mail however, you can do futher testing if it will work with the Notification style of sending mail.


First things first, create a new mail class:

php artisan make:mail InvoicePaid

Where InvoicePaid is the name of your intended mail class. This will create InvoicePaid.php inside app/Mail if Mail folder doesn’t exist, don’t worry, it will be created automatically.

Inside your mail class, you will have something like this:

<?php

namespace
App\Mail;

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

class NewJudgementFileUploaded extends Mailable
{
use Queueable, SerializesModels;

/**
* Create a new message instance.
*
*
@return void
*/
public function __construct()
{
//
}

/**
* Build the message.
*
*
@return $this
*/
public function build()
{
return $this->view('emails.invoice');
}
}

In the build method, you can either create the view or fix the view to a default Laravel markdown (run this php artisan command instead of the first one in order to generate a view and the Mail class together):

php artisan make:mail InvoicePaid --markdown=emails.invoice.paid

public function build()
{
return $this->markdown('emails.invoice.paid');
}

To attach a single file:

public function build()
{
return $this->markdown('emails.invoice.paid')
->attach('/path/to/file');
}

To attach multiple files:

public function build()
{
$files = []; // array of all files to be attached

$message = $this->markdown('emails.invoice.paid');

foreach ($files as $file) {
$message->attach($file) // attach each file
}
    return $message; //Send mail
}

Simple yeah? I know. Note that this can be used to attach files uploaded directly through a form, just make sure you pass the $request->file() into the $files.

Thanks for reading and sorry if it doesn’t satisfy you to the fullest, I tried to make it as comprehensible as possible (in my own way). The basic feature applied is the foreach loop.