Laravel Mail - PathToFile variable not found - php

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);
});

Related

How to resolve this error: Argument 1 passed to Zend_Mail_Message::__construct() must be of the type array, none given

My code in controller:
`
public function filetransport()
{
set_time_limit(0);
$message = new Zend_Mail_Message();
$message->addTo('matthew#zend.com')
->addFrom('ralph.schindler#zend.com')
->setSubject('Greetings and Salutations!')
->setBody("Sorry, I'm going to be late today!");
// Setup File transport
$transport = new Zend_Mail_Transport_File();
$transport->setOptions(array(
'path' => 'data/mail/',
'callback' => function (Zend_Mail_Transport_File $transport) {
return 'Message_' . microtime(true) . '_' . mt_rand() . '.txt';
},
));
$transport->send($message);
}
While creating instance of Zend_Mail_Message it is throwing error.The Error is
Catchable fatal error: Argument 1 passed to Zend_Mail_Message::__construct()
must be of the type array, none given,
called in C:\xampp\htdocs\Zend-Mailer\application\controllers\IndexController.php on line 102
and defined in C:\xampp\htdocs\Zend-Mailer\library\Zend\Mail\Message.php on line 57
If you have idea about this please let me know.....!
According to Zend documentation Zend_Mail_Message accepts one argument as the parameter. You are not passing any parameter. That is why you get this error.
__construct(array $params)
In addition to the parameters of Zend_Mail_Part::__construct() this
constructor supports:
file filename or file handle of a file with raw message content
flags array with flags for message, keys are ignored, use constants defined in Zend_Mail_Storage
Inherited_from \Zend_Mail_Part::__construct()
From Zend_Mail_Part docs,
Zend_Mail_Part supports different sources for content. The possible
params are:
handler a instance of Zend_Mail_Storage_Abstract for late fetch
id number of message for handler
raw raw content with header and body as string
headers headers as array (name => value) or string, if a content part is found it's used as toplines
noToplines ignore content found after headers in param 'headers'
content content as string
That means, as the error is saying, you are missing the params array in the constructor.

Why can't I use 'require' with 'array_map'?

I've tried to include the contents from a list of files:
$files = [
'a.php',
'b.php',
];
$contents = array_map('require', $files);
But this didn't work. The error I get is:
Warning: array_map() expects parameter 1 to be a valid callback, function 'require' not found or invalid function name
Why is this and is there a way to make it work?
Because require isn't a function, it's a language construct.
You'll need to create a valid callback function to do the actual require, or use an autoloader
As everyone already noticed - it is a language construct.
You can try this
$includes = array('a.php', 'b.php');
array_map(function($file){
require $file;
}, $includes);
Agree with Mark Baker as it's not function , You can use _autoload() in case you are including class files.
use autoload or spl_autoload_register
to comfort work use namespaces
or you may use array_wallk without return value and anonunys function
`$files` = [
'a.php',
'b.php',
];
`$contents` = array_map(`$files`, function(`$el`){
require(`$el`);
});
//but foreach working faster:
foreach(`$files` as `$item`){
require(`$item`
);}`

Laravel - Mail fails when email address is in variable, works when hardcoded

Im using Laravel class Mail to send emails to customer:
$item = DB::table('questions')->find($id);
var_dump($item->email);
// send mail to customer
Mail::queue('emails.email', $data, function($message) {
$message->to($item->email)->subject('Odpoveď od SCSPPIMKA');
$message->sender('mailer#scspimka.sk');
});
When I hardcode email address in $message->to('example#email.com') everything works fine, but when I use email address in variable: $message->to($item->email) I get error:
Undefined variable: item' in /data/www/scsppimka.local/laravel/vendor/jeremeamia/SuperClosure/src/Jeremeamia/SuperClosure/SerializableClosure.php(99) : eval()'d code:2
Vardump of $item->email shows string with correct e-mail address. What can cause this problem?
You need use use to take $item variable from current context to the context of the anonymous function:
Mail::queue('emails.email', $data, function($message) use ($item) {
$message->to($item->email)->subject('Odpoveď od SCSPPIMKA');
$message->sender('mailer#scspimka.sk');
});

Laravel 4 Queued Mailing throws error while directly sending works

I have a Laravel 4 app where I need to send certain emails to users. I have no idea why but I keep getting this error on my test server (it does not happen on my local vagrant box)
Argument 1 passed to Illuminate\Mail\Mailer::getQueuedCallable() must
be of the type array, null given, called in
blablabla/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php
on line 238 and defined
I tried resetting everything: database, clean clone from git. None of these worked. I also cleared my browser cache and cookies out of desperation. I am using Sync queue. So it's not even an actual queue.
Mail::send works just fine. Mail::queue throws the error above.
I literally started to pull my hair out so any help will be greatly appreciated.
Here is my code:
This is my BookingMailer class that extends Mailer class.
// partner bir arabanın rezervasyonuna onay verdiğinde müşteriye gönderilecek ödeme linki
public function sendPaymentLinkToCustomer($customer, $partner, $booking) {
$view = 'emails.bookings.request_confirmed';
$data = [
'user' => $customer->full_name // string,
'partner' => $partner->display_name // string,
'reference' => $booking->reference // integer,
'booking_id' => $booking->id // integer
];
return $this->sendTo($customer, 'Booking Request Confirmed', $view, $data, true, true);
}
And this is my Mailer class that actually queues the mail.
public function sendTo($user, $subject, $view, $data = array(), $admin_copy=false, $send_as_pm=false)
{
Mail::queue($view, $data, function ($message) use ($user, $view, $data, $subject, $admin_copy) {
$message = $message->to($user->email)->replyTo(Config::get('mail.from.address'), Config::get('mail.from.name'))->subject($subject);
return $message;
});
}
Here is the solution to this problem (at least in my case)
I was including the user first and last name to the mail. I was only showing the first letter of the last name, though. And I was using substr for a UTF-8 string, and that's why sometimes it returned problematic characters that get inside the data array and ultimately cause the queue to break.
When i used mb_substr instead of substr, my problem disappeared.
Phew, I thought I would never figure this one out on my own.

preg_replace not retrieving correct data

I'm using my own cms from scratch, so, i'm adding useful functions for my system, but i got stuck on this:
A phrase is being loaded from lang file on array, in this case, $lang['sign']['server'] = 'Sign in with your {{servername}} registered account:';, and then, by a function, {{servername}} must be replaced by $config['servername'].
What i have so far on my functions class is the following:
public function replaceTags($text)
{
global $config;
return preg_replace("/{{(.*?)}}/" , $config[strtolower("$1")], $text) ;
}
Im calling this function here: $main->set('ssocial', $FUNC->replaceTags($lang['sign']['social']));, but the result is Sign in with your registered account: instead of Sign in with your "Server Name Goes Here" registered account.
Any ideas about why the preg_replace is not retrieving the value?
Also, when $config[”$1”] is inside '' like this '$config[”$1”]', the output is Sign in with your $config[”servername”] registered account:, so i have no clues about what's wrong.
Thanks in advance.
This is a quick and dirty working example using preg_replace_callback
<?php
$config = array('server' => 'my custom text');
function handler($matches){
global $config;
return $config[$matches[1]];
}
function replaceTags($text)
{
return preg_replace_callback("/{{(.*?)}}/" , 'handler', $text) ;
}
print replaceTags("Hello {{server}}");
Output:
Hello my custom text
As for why your code doesn't work: the second parameter of preg_replace is $config[strtolower("$1")], so php will literally look for key "$1" in $config, which probably doesn't exist.

Categories