Stevan Lai Stevan Lai - 3 months ago 29
PHP Question

Laravel Email Attachment

I have an error i think here.

$file = $request->file('upload_cv');

$fileName = $file->getClientOriginalName();

$request->file('upload_cv')->move("cv/", $fileName);

$tambah->upload_cv = $fileName;

$tambah->save();

$email = DB::table('user')->where('email');

Mail::send('emails.welcome', array(
'email' => $request['email'],
'HP' => $request['kontak'],
'nama' => $request['nama'],
'posisi' => $request['posisi'],
'CV' => $tambah->upload_cv = $fileName
), function ($message) use ($request, $tambah, $email, $file)
{
$message->from('MYEMAIL@gmail.com', $request->posisi);
$message->to('THEIREMAIL@gmail.com')
->subject('Lamaran Baru')
->cc('SOMEPERSON@yahoo.com.sg')
->attach($file)
->replyTo($request->email);

$message->getSwiftMessage();
});

return redirect()->to('index');


The error happens when I click submit, it loads forever stuck on the current form. If I remove the
->attach($file)
it will be redirect to index, which means it worked. But if I put the
->attach($file)
its always loading and still on the current page.

Please explain what is going wrong,Thanks before.

Answer

attach method expects path to file but you are passing the UploadedFile instance from your request directly. Instead use the path of the file so laravel can find and attach it to your mail.

You've to pass full path of your file. For example, if you are uploading your file in project root inside cv folder. e.g.

  • Project Root
    • cv

Then you can write it like this.

->attach( base_path( "cv/" . $file->getClientOriginalName() ) );