Search code examples
phpemaillaravellaravel-4function-parameter

Sending variables inside the function in laravel


Is it possible to get the value of the $string which is stored outside the function (For Mail)

Here i tried.

$string = str_random(5);     

Mail::send([], [], function($message,$string)
    {
        $user = MailTemplate::find(1);
        $mail_body = $user->MailContent;
        $mail_body = str_replace("{password}", $string, $mail_body);
        $message->setBody($mail_body, 'text/html');
        $message->to(Session::get('sess_mail'));
        $message->subject('Password Details - Ma$na Taxi');
    });

But it shows error

Missing argument 2 for LoginController::{closure}()

How can i pass the value of $string inside the mail function like

Mail::send([], [], function($message,$string)

So it should be accessible at $mail_body = str_replace("{password}", $string, $mail_body);


Solution

  • Your call to the static method Mail::send() needs to match the signature specified here - http://laravel.com/docs/4.2/mail#basic-usage

    $string = str_random(5);     
    
    Mail::send('name-of-view-used-for-email',
         array('foo' => $string), function($message) use ($string)
        {
            $user = MailTemplate::find(1);
            $mail_body = $user->MailContent;
            $mail_body = str_replace("{password}", $string, $mail_body);
            $message->setBody($mail_body, 'text/html');
            $message->to(Session::get('sess_mail'));
            $message->subject('Password Details - Ma$na Taxi');
        });
    

    How can i pass the value of $string inside the mail function like so it should be accessible at $mail_body = str_replace("{password}", $string, $mail_body);

    You have a scope issue - in order to get be pass $string you need to use use ($string) before your function call.
    As Ive shown in the updated code.