Search code examples
laravellaravel-5laravel-mail

Laravel Mail: attach if not null


I am sending emails using the mailable class of Laravel. I want to attach files, if the files exist. So I only want to add the attach parameter if the file exists. I could work with if/else clauses, but I have different files and that would not be clean. A attachIfNotNull function (which does not exist) would be helpful in this case, but maybe there are other clean solutions..

    public function build()
    {
        return $this->view('emails.orders.shipped')
                    ->attach('/path/to/file1', [
                        'as' => 'name.pdf',
                        'mime' => 'application/pdf',
                    ]);
    }

Solution

  • You can use File::exists() or Storage::exists():

    $view = $this->view('emails.orders.shipped');
    return \File::exists('/path/to/file1') ? $view
         : $view->attach('/path/to/file1', [
             'as' => 'name.pdf',
             'mime' => 'application/pdf',
         ]);