I am writing this simple code to send a mail with attachment, however, I am not able to pass the path to the file variable.
$pathToFile = "Sale-".$id.".csv";
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});
The above code throws:
Undefined variable: pathToFile
Also, I tried passing a variable (added $pathToVariable with $message in above closure) to the closure but it throws following error:
Missing argument 2 for SaleController::{closure}()
It basically doesn't identify any variable outside the closure. Can anyone please help me out here?
You can try this:
$pathToFile = "Sale-".$id.".csv";
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message) use ($pathToFile)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});
The instruction:
use ($pathToFile)
...allows you to use your variable in the closure.
When referencing $pathToFile within your closure, the script is looking for $pathToFile to be declared within the closure. As no declaration exists, you see the undefined variable error.
Any variable used inside a function is by default limited to the local function scope.
Source: http://www.php.net/manual/en/language.variables.scope.php
To fix it you should be able to pass $pathToFile into your closure, e.g.:
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message, $pathToFile)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});