Search code examples
phplaravelemaillaravel-artisan

Laravel : I can't use Request object two times at the same function


I'm trying to build contact form and I want it to send the user message for the website email and i want it to send message for the user mail inform him that his message received so I'm using this code in controller :

 public function mail(Request $request) {
     Mail::send('mail.mail', ['name'=>"$request->name" , 'email'=>"$request->email" , 'msg'=>"$request->message"], function($message) {
         $message->to('housma.elma@gmail.com', 'Housma')->subject('Housma.com enquiry');
     });

     Mail::send('mail.mailResponse', ['name'=>"$request->name"  ], function($message ) {
        /*line 29 */    
        $message->to("$request->email", "$request->name")->subject('Housma.com : Auto reply');
     });

     return Redirect::to('/contact')->with('successful', 'Your message has been sent');
}

The first message for my email is working fine, but when Laravel reaches the second message, I get this error

ErrorException in pagesController.php line 29: Undefined variable: request


Solution

  • Replace line 28 with

    Mail::send('mail.mailResponse', ['name'=>"$request->name"  ],
     function($message) use($request) {
    

    In PHP, if you want to use a variable in a closure, you need to use use ($variablename)