Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return error message to a database field: Yii2 and Swiftmailer

I program in PHP using the Yii2 framework and Swiftmailer.

I am trying to find a way to update a database field with error messages. When a user is trying to create an account, and the email he declares is not a valid one, the field FailMesg should be updated with the error message. I have tried two different ways to do it but none seems to work (the database field remains NULL):

1st ( Include variable in send() method)

$message = Swift_Message::newInstance()
    ->………..
$transport = ………………
$mailer = Swift_Mailer::newInstance($transport);
if($mailer->send($message, $failures)){
    ……..
else
    ……..
    $user->FailMesg = $failures;
........
$user->save();

2nd (Use the Logger plugin)

$message = Swift_Message::newInstance()
    ->………..
$transport = ………………
$mailer = Swift_Mailer::newInstance($transport);
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
if($mailer->send($message)){
    ……..
else
    ……..
    $user->FailMesg = $logger->dump();
........
$user->save();

Am I missing something here? Any suggestions will be highly appreciated.

like image 334
YorKal Avatar asked Dec 02 '25 10:12

YorKal


1 Answers

$failures is an array, not a string. From the swiftmailer docs:

If the variable name does not yet exist, it will be initialized as an empty array and then failures will be added to that array. If the variable already exists it will be type-cast to an array and failures will be added to it.

You have to change it into a string before saving e.g.:

$user->FailMesg = implode("|", $failures);
like image 85
topher Avatar answered Dec 05 '25 00:12

topher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!